cancel
Showing results for 
Search instead for 
Did you mean: 

is there an equivalent of the mockMvc class for dotnet integration testing

The guides I’ve seen either mock out the data layer / services and unit test controllers or have a lot of repetitive setup where they effectively reconfigure the app for testing an API as a whole. In both cases I’m concerned about env parity where there can be drift between the configuration defined in the app and tests.

In spring testing they exposed a mockMvc class that would start the server as defined by the app config and then allow you to make requests and assertions against it. You could either supply a connection string to hit a test DB or override it with an in-memory one. This gave a better sense of behavior as everything was “real” short of virtualizing the networking stack.

Is there an equivalent for testing an ASP.NET core API? For now I have been testing externally using postman/Newman to get closer to reality. Is that a common approach or are there benefits of integrated tests?

2 REPLIES 2

 

Integration tests ensure that an app's components function correctly at a level that includes the app's supporting infrastructure, such as the database, file system, and network. ASP.NET Core supports integration tests using a unit test framework with a test web host and an in-memory test server.

Obrien45050
Member

The problem is that if I use the code below, it still executing the Program.cs which in my case has custom middleware that I dont want executed in my tests. How do I go about to create a custom Program class, that DONT execute my main Program.cs:

public async Task HelloWorldTest()
{
    var application = new WebApplicationFactory<Program>()
        .WithWebHostBuilder(builder =>
        {
            // ... Configure test services
        });

    var _client = application.CreateClient();
    var response = await _client.GetAsync("localhost://home");
}```

Reference: https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2

Check out the documentation on integration tests and mock up your "custom middleware".

Documentation:

https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0 /echatspin /echatrandom

 I hope this helped you some on the way.