In my last post, I showed how to work with controllers and actions. This included passing data, return types of actions and redirects. In this post, I want to check if my implemented features work as I expect them to by unit testing controllers and actions.
I use the project which I created the last time. For the testing, I add a class library project called ControllersAndActions.Test. In this project, I add one class called ActionTests. Usually, I would use several classes for every class I test. To make things simple, I only use this one class this time. After creating the class, I install xUnit and FluentAssertions. You can choose the testing framework of your liking. FluentAssertions is a great tool to make the asserts more readable.
The first tests I write will test what view is returned by the action. To do that, I call an action and then the view name of the returned value should be the name of the view I expect to be called.
If your action returns an ActionResult instead of a ViewResult, you have to cast the object first before you can access the ViewName property.
More interesting than testing if the right view, is called is testing the values of the view bag. You can access the view bag with the returned object of the action and compare it with the value you expect it to be.
When testing the redirect to a controller, the return object of the action has two interesting properties when testing redirects. The first property is Permanent which is a bool indicating whether the redirect was permanent. The second property is URL which you can compare to the URL you expect.
Testing the redirection to a route is a bit different. You have to compare the route values for the controller and action to the values you expect them to be.
The next interesting property in the return object is the status code. With this property, you can check if the returned HTTP status code is what you expect.
The last test for today tests if the view model has the expected data type. To do that use the ViewData.Model property of the return value.
In this post, I presented several test cases for unit testing controller and actions. For these tests, I accessed various properties of the return object of the action call.
You can find the source code on GitHub.