Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check an action's call to View() has not thrown an exception?

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.

like image 233
gingerbreadboy Avatar asked Oct 10 '22 13:10

gingerbreadboy


1 Answers

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:

  • Action returns the default view;
  • Action passes the correct model for the view.

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.

like image 129
João Angelo Avatar answered Oct 13 '22 12:10

João Angelo