测试 ASP.NET MVC 视图模型
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,它不测试(仅?)框架。它测试执行操作会产生一个由非空集合组成的 ViewModel,该集合的计数与模拟中提供的计数相同。
您可以将最后一个条件简化为
,甚至
我的意思是它是一个单元测试,其中有一些硬编码值是正常的。
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
or even
I mean it's a unit test, it's normal to have some hardcoded values in there.