测试 ASP.NET MVC 视图模型

发布于 2024-08-07 10:48:19 字数 747 浏览 3 评论 0原文

我正在使用 Nunit 和 Moq 来测试我的 asp.net mvc 解决方案。这是测试传递给视图的模型是否是正确的对象/集合的好方法吗?

[Test]
public void Start_Page_Should_Display_Posts()
{
    var posts = new List<Post> {new Post {Id = 1}, new Post {Id = 2}};

    var mock = new Mock<IRepository>();
    mock.Setup(x => x.FindAll<Post>()).Returns(posts.AsQueryable());

    var controller = new PostsController(mock.Object);
    var result = controller.Index(null) as ViewResult;
    var viewModel = controller.ViewData.Model as IEnumerable<Post>;

    Assert.IsNotNull(result);
    Assert.IsTrue(viewModel.Count() == mock.Object.FindAll<Post>().Count());
}

我知道这是对框架的测试,但希望您能明白我的意思。我可以相信这个测试吗?

目前我有点累,所以请毫不犹豫地要求详细说明。

谢谢

I'm using Nunit and Moq to test my asp.net mvc solution. Is this a good way to test that the model passed to the view is a correct object/collection?

[Test]
public void Start_Page_Should_Display_Posts()
{
    var posts = new List<Post> {new Post {Id = 1}, new Post {Id = 2}};

    var mock = new Mock<IRepository>();
    mock.Setup(x => x.FindAll<Post>()).Returns(posts.AsQueryable());

    var controller = new PostsController(mock.Object);
    var result = controller.Index(null) as ViewResult;
    var viewModel = controller.ViewData.Model as IEnumerable<Post>;

    Assert.IsNotNull(result);
    Assert.IsTrue(viewModel.Count() == mock.Object.FindAll<Post>().Count());
}

I understand that this kind of tests the framework, but hopefully you'll get my point. Can I trust this test?

Currently i'm a bit tired so don't hesitate to ask for an elaboration.

Thanks

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

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

发布评论

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

评论(1

幽蝶幻影 2024-08-14 10:48:19

不,它不测试(仅?)框架。它测试执行操作会产生一个由非空集合组成的 ViewModel,该集合的计数与模拟中提供的计数相同。

您可以将最后一个条件简化为

Assert.IsTrue(viewModel.Count() == posts.Count);

,甚至

Assert.IsTrue(viewModel.Count() == 2);

我的意思是它是一个单元测试,其中有一些硬编码值是正常的。

No it doesn't test (only?) the framework. It tests that executing the action results in a ViewModel consisting of a not-null, collection of the same count as the one supplied in the mock.

You could simplify the last condition into

Assert.IsTrue(viewModel.Count() == posts.Count);

or even

Assert.IsTrue(viewModel.Count() == 2);

I mean it's a unit test, it's normal to have some hardcoded values in there.

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