In the last post I talked about using and extending IActionResult to return your preferred HttpStatus code in your ASP.NET MVC controllers. But how do you write unit tests that make sure that you’re returning what you expect? Your controllers will return one of these:
IActionResult
There’s nothing on this interface that you can easily tie back to the status code. All of the functions that we return in a controller implement this interface, though, so they qualify as valid return objects from our controller actions.
So, all we need to do to make sure we’re getting the right result is cast the result from our test. If it’s a return type that includes some kind of content, you’ll want to check to make sure that the content is the type that you expect, and then return that object for further assertions.
I like to put this in to a base class that can then be inherited by any subsequent controller test class.
ControllerTestBase
If you want to make it even easier on yourself, you can add some helper methods for each of the return types that you regularly test:
ControllerTestBase (extended)
This makes it so all you need to provide is the IActionResult and the base class will handle verification.