Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

[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

like image 757
alexn Avatar asked Oct 13 '09 20:10

alexn


People also ask

How and what we will test in MVVM?

MVVM – Unit Testing The idea behind unit testing is to take discrete chunks of code (units) and write test methods that use the code in an expected way, and then test to see if they get the expected results. Being code themselves, unit tests are compiled just like the rest of the project.

How do I access model value in view?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.

Which is better NUnit or MsTest?

The main difference is the ability of MsTest to execute in parallel at the method level. Also, the tight integration of MsTest with Visual Studio provides advantages in both speed and robustness when compared to NUnit. As a result, I recommend MsTest.

What is ASP.NET MVC unit testing?

ASP.NET Core API. In computer programming, unit testing is a software testing method by which individual units of source code are tested to determine whether they are fit for use.


1 Answers

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.

like image 183
Andrei Rînea Avatar answered Oct 21 '22 06:10

Andrei Rînea