Testing ASP.NET MVC View Model

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?

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.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.


13.10.2009 20:19:10

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.

13.10.2009 21:13:51