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:
- public ViewResult IndexNamed()
- {
- return View("IndexNamed");
- }
- public ViewResult Index()
- {
- return View();
- }
- [TestCategory("Build"), TestCategory("Unit"), TestMethod]
- public void IndexNamed()
- {
- // Arrange
- string expected = "IndexNamed";
- string actual;
- var controller = new AdminController();
- // Act
- var result = controller.IndexNamed() as ViewResult;
- // Assert
- actual = result.ViewName;
- Assert.AreEqual(expected, actual);
- }
- [TestCategory("Build"), TestCategory("Unit"), TestMethod]
- public void Index_Not_Named()
- {
- // Arrange
- string expected = "Index";
- string actual;
- var controller = new AdminController();
- // Act
- var result = controller.Index() as ViewResult;
- // Assert
- actual = result.ViewName;
- Assert.AreEqual(expected, actual);
- }
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 Reply