使用 Rhino Mocks 模拟 ASP.NET MVC2 中的控制器操作

发布于 2024-10-10 01:56:21 字数 355 浏览 0 评论 0原文

我无法理解如何有效且高效地为一个简单的控制器操作构建模拟单元测试,该操作创建视图模型的实例并将其传递给视图。

    public ActionResult Index()
    {
        IndexViewModel viewModel = new IndexViewModel();

        return View(viewModel);
    }

有人可以告诉我如何为控制器操作编写单元测试,以确保该操作生成视图模型类的实例,并将其分配为视图的模型。

当然,我理解 TDD 说我应该先编写测试,然后构建上面的内容,但我在掌握基础知识时遇到了困难。对您传递的任何代码的解释也很棒。谢谢

I am having trouble understanding how I can effectively and efficiently building a mocking unit test for a simple controller action that creates an instance of a viewmodel and passes it to a view.

    public ActionResult Index()
    {
        IndexViewModel viewModel = new IndexViewModel();

        return View(viewModel);
    }

Can someone please give me an idea how I would write a unit test for a controller action that would ensure that the action generates an instance of a viewmodel class, and assigns it as the model for the view.

I understand, of course, that TDD says I should write the test first, and then build the above, but I having trouble grasping the fundamentals. An explanation of any code you pass on would be great, too. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗恋未遂 2024-10-17 01:56:21

这只是一个简短的示例,说明您可以执行以下操作来测试此内容:

    [TestMethod]
    public void IndexGetMethodReturnsIndexViewModel()
    {
        // Arrange
        HomeController controller = new HomeController();

        // Act
        ViewResult result = controller.Index() as ViewResult;
        var viewModel = result.ViewData.Model as IndexViewModel;

        // Assert
        Assert.IsNotNull(viewModel);
    }

因此,您在控制器上调用 Index 方法,访问 viewModel 并确保它的类型为 IndexViewModel,然后断言它不为 null。

希望这有帮助。

This is just a brief example of what you could do to test this:

    [TestMethod]
    public void IndexGetMethodReturnsIndexViewModel()
    {
        // Arrange
        HomeController controller = new HomeController();

        // Act
        ViewResult result = controller.Index() as ViewResult;
        var viewModel = result.ViewData.Model as IndexViewModel;

        // Assert
        Assert.IsNotNull(viewModel);
    }

So you are calling the Index method on the controller, accessing the viewModel and making sure it is of type IndexViewModel and then you assert that it is not null.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文