How can i unit test the view of an ASP MVC application?
I have tried the mvc contrib test helper...
_controller.Index().AssertViewRendered();
but this doesn't actually test the view.
for example i can happily insert some bogus code in the view, and get the dreaded yellow screen of death, without my unit test ever knowing about it.
Is there any estabilished method of doing this? Do i need a mock out the view engine? Does mvccontrib cater to this?
I would have thought this would be a very common requirement, but i can't find much about it!
Thanks
EDIT What i'm really after is compile time checking, to ensure that model changes don't impact the view.
this question contained the instructions to enable build time view compilation which is sufficient for me for now. Compile Views in ASP.NET MVC
To make your Unit Test load the UIViewController that has an interface XIB file is even easier. Create an instance on UIViewController that uses XIB file. Make sure though that the view controller and the XIB files have the same names. Call the loadViewIfNeeded() method to make the viewDidLoad() execute.
We create the data access logic in a separate class, or set of classes, called a repository, with the responsibility of persisting the application's business model. As the Repository Pattern is useful for decoupling entity operations from presentation, it allows easy mocking and unit testing.
There are 3 options:
It is possible to test your views via unit test using Visual Studio Test Tools, but only the values, created by the controller (e.g. values in ViewBag: ViewBag.message = "My message."
) or the name of the rendered view:
[TestMethod]
public void MyActionTest()
{
// Arrange
var lController = new HomeController();
// Act
var lResult = lController.MyAction() as ViewResult;
// Assert
Assert.IsTrue(lResult.ViewBag.message == "My message.", "Wrong Message in Viewbag.");
Assert.IsTrue(lResult.ViewName == "MyView", "Incorrect view.");
}
If you want to auto-test your entire view inclunding HTML, I recommend Selenium IDE as fast and simple solution and Selenium Web Driver for cross-browser-tests and experts.
Unit tests normally never test UI because it's simply too brittle to do so.
While you could argue that a minum test would be that the View doesn't crash with an exception when we attempt to render it, this would also be about the only unit test we could actually write for a View (ASP.NET MVC, WPF, Windows Forms, etc. - it doesn't really matter).
The next thing you (or your customer) would want to test is that the View is rendered correctly, and you can't reliably do this with an automated test. What it all boils down to is that Views are better tested by Visual Inspection because the return of investment on that is simply better than trying to develop and maintain automated UI tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With