If we hit SomeController.SomeAction()
but the file SomeAction.cshtml isn't found we get a System.InvalidOperationException and the output error message...
The view 'SomeAction' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...etc
However, even with this file missing the test below will pass as a ViewResult is still being returned.
What is the best way to check the action's call to View()
has not thrown an exception and quietly returned this in ViewResult content?
public class SomeController: Controller
{
public ActionResult SomeAction()
{
var viewModel = new SomeModel();
return View(viewModel);
}
}
[Test]
public void TestIndex(Type clientType)
{
var controller = new SomeController();
var result = (ViewResult)controller.SomeAction();
Assert.That(result, Is.TypeOf<ViewResult>());
}
NOTE: This is a trivial example of a bigger problem, there is good reason to perform this kind of test at this point but this is not the forum for that discussion.
In my opinion you should not be trying to assert if a view exists in the unit test for a controller action. What you need to test is the controller action behavior which in this case is pretty simple, as it should be. So you would have tests for:
Also, as a sidenote, if you have a test that casts the result of the action to ViewResult
you might as well be explicit about it and change the return type of the action. This change makes your code clearer and also eliminates the need for the sample test you presented which has a bug, since if the cast fails the assert code is not reached and if the cast succeeds the assert is redundant.
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