• Post Calendar

    May 2010
    S M T W T F S
    « Apr   Sep »
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031  

Unit Testing a Very Simple ViewResult in MVC

Technorati Tags: ,,

I have a view that really only provides content, is there a quick way to test that it exists? What’s the Assert?

There’s really not much to unit test if you have a page that has only HTML in a MVC (Model-View-Controller) project. And to some extent, if you had a test that called it, if someone removed that View from the controller, the test would no longer compile. However, I don’t like having tests without an Assert. So here are two views called in slightly different ways. One is more testable than the other:

The two views…
  1. public ViewResult IndexNamed()
  2. {
  3.     return View("IndexNamed");
  4. }
  5.  
  6. public ViewResult Index()
  7. {
  8.     return View();
  9. }

 

The Passing Test
  1. [TestCategory("Build"), TestCategory("Unit"), TestMethod]
  2. public void IndexNamed()
  3. {
  4.     // Arrange
  5.     string expected = "IndexNamed";
  6.     string actual;
  7.     var controller = new AdminController();
  8.  
  9.     // Act
  10.     var result = controller.IndexNamed() as ViewResult;
  11.  
  12.     // Assert
  13.     actual = result.ViewName;
  14.     Assert.AreEqual(expected, actual);
  15. }

 

The FAILING Test
  1. [TestCategory("Build"), TestCategory("Unit"), TestMethod]
  2. public void Index_Not_Named()
  3. {
  4.     // Arrange
  5.     string expected = "Index";
  6.     string actual;
  7.     var controller = new AdminController();
  8.  
  9.     // Act
  10.     var result = controller.Index() as ViewResult;
  11.  
  12.     // Assert
  13.     actual = result.ViewName;
  14.     Assert.AreEqual(expected, actual);
  15. }

The second test fails with this error message:

Assert.AreEqual failed. Expected:<Index>. Actual:<>.

I’m not sure why the ViewName is not automatically set when you user the View() method, but it’s not. You have to call it with the name so now I’m in the habit of always calling it with that. Perhaps if I have some other need to implement my own controller base class I’ll change that behavior.

Leave a Comment