When testing .NET controllers I can test the details of the controller methods themselves, and I can test that the correct model and data are returned in the results from the controller actions - but I can't find a good way to test the content of the Html that will be returned.
It would be really handy to be able to render the vewiresult into an html string so that I could make assertions against that html (.e.g Has an H1 with specific text).
This can be done by deploying and configuring an instance of the app and then using a browser test runner to call the controller action and render the result and then make assertions against the page content - but this seems needlessly heavy handed and fragile (not to mention slow).
All the Html generation seems really awkwardly tangled and coupled with the framework and relies on finding flies in specific folders on disk and other deployment level concerns.
How can I write a test against the HTML results without deploying the app?
As Mushroomator writes in the comment, you can write self-hosted integration tests in ASP.NET, using WebApplicationFactory.
Here's an example from the blog post linked above:
[Fact]
public async Task ReserveTableAtNono()
{
using var api = new SelfHostedApi();
var client = api.CreateClient();
var at = DateTime.Today.AddDays(434).At(20, 15);
var dto = Some.Reservation.WithDate(at).WithQuantity(6).ToDto();
var response = await client.PostReservation("Nono", dto);
await AssertRemainingCapacity(client, at, "Nono", 4);
await AssertRemainingCapacity(client, at, "Hipgnosta", 10);
}
See the article for more details. That one tests against a REST API, but since the client
is a normal HttpClient, you can also use it to request HTML pages.