Reputation: 3030
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
Upvotes: 1
Views: 303
Reputation: 765
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.
Upvotes: 1