Welcome to Part 4 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 1 – Automated ASP.NET MVC Testing
Part 4 – Testing View Rendering
Part 5 – Automated Functional UI Testing
Part 6 – Running Tests on TeamCity Continuous Integration Server
Part 7 – Further Learning
Testing View Rendering
Testing Razor Views in Isolation
Jason explains that our objective is not to test Controllers, Services or Databases, just our views in isolation.
We can test that:
- The ViewBag content renders correctly
- The strongly typed model items are rendered correctly
- The conditional logic in the view behaves correctly
Overview of View Rendering Testing
Jason explains the plan:
- Install the Razor Generator extension for Visual Studio
- Use it to compile our view into C# code
- Instantiate this code in our unit test
- Use the companion Razor Generator testing library
This demo shows us how to:
- Add a view tests project
- Install Razor Generator extension
- Install Razor Generator testing package
- Set Home Index view to compile to Index.generated.cs
Creating an Initial Test
We see how to write the test ShouldRenderLoanInterestRate. In this test we render our model as HTML and write assertions against the HtmlDocument object.
Testing ViewBag Message Rendering
We write ShouldRenderMainMessage to check that we’re outputting our ViewBag message in the correct place.
As with the previous test, this uses the GetElementById method to get the InnerText of an element within our HtmlDocument object.
Testing View Logic
We have some logic in our ApplicationStatus view to output a different span depending on where the loan is accepted.
We can test this in much the same way as we have already seen – we just setup our model, render it as html and assert that the HTML meets our expectations.
Next Jason shows how to refactor the test to test the expected element id rather than the expected inner text.
When we’re testing with Razor Generator, we only get the HTML for the view that we are working with, not any partial view rendered HTML.
@Html.DisplayFor is treated as a partial view.
To test this, there’s an alternative approach we can take…
Testing Full Views with Approvals
This is a long-winded process which can’t be summarized meaningfully.
Jason has produced a whole course explaining Approval Tests.