Welcome to Part 3 of this review of the Pluralsight course Automated ASP.NET MVC Testing: End to End by Jason Roberts.
With over 15 years industry experience, Jason is a Microsoft .NET MVP who has has written multiple books including Clean C#, and C# Tips. He is also an open source contributor and the creator of FeatureToggle.
Also in this series:
Part 7 – Further Learning
Types of Controller Action Tests
- Default view
- Specific view
- Specified HTTP status code
- Redirect to URL
- Conditional view depending on model state
- Correct model supplied to view
To Test or Not to Test?
Jason discusses when we might want to write tests against our controllers:
- When we have complex “fat” controllers
- High value / high risk logic
- Team should decide on the benefit of testing vs risk of not testing
Writing a Controller Test Manually
In this demo we:
- Add a controller tests project
- Create a class LoadApplicationControllerTests
- Apply the NUnit TextFixture attribute
- Write a manual default view test: ShouldRenderDefaultView
- Install MQ and create fake controller dependencies
- Assert that the view name is “Apply”
Fluent MVC Testing is an open source project that allows us to write shorter, terse and fluent style test code.
Jason explains that this isn’t tied to NUnit – we can use it with XUnit or MSTest if we wish.
Refactoring to Use FluentMVCTesting
In this demo we:
- Install FluentMVCTesting from NuGet
- Refactor manual test
- Remove the need for the “Apply” magic string
- Use sut.WillCallTo()
- Use the .ShouldRenderDefaultView() fluent method
Adding Additional LoanApplicationController Tests
We begin with a look at the Apply method we want to test, which either redirects to an “Accepted” or “Declined” action.
We see how to write the tests:
Adding HomeController Tests
We learn how to write ShouldRedirectToPluralsightForContact.
With the FluentMVCTesting library, this is pretty easy. We use the .ShouldRedirectTo method.
Adding LoanApplicationSearchController Tests
This final demo creates some tests for our LocationApplicationSeachController.