Mike Tkachev
Mike Tkachev

Reputation: 31

Debug .NET Core API from xUnit

I have developed two projects based on .NET Core 2.1.

  1. WebAPI
  2. xUnit

WebAPI uses IIS as a hosting platform. xUnit connects to WebAPI using the HttpClient class to use the http.

I tried to connect to the w3wp service to catch the Get method in the controller, but it was not successful. In addition, I started another one environment and run Debug in the WebAPI project, but this did not help.

Who knows where the problem is and how to solve it?

Upvotes: 0

Views: 1676

Answers (1)

Alexey Adadurov
Alexey Adadurov

Reputation: 184

There is a great guide on learn.microsoft.com on how to do just that: https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.1

Basically, you need to install the Microsoft.AspNetCore.Mvc.Testing package into your test project and derive an 'test app factory' class from WebApplicationFactory in your testing project. Then in each of your test classes you'll want to create an instance of the class and then use WebApplicationFactory.CreateClient to get an instance of HttpClient. Then you use the HttpClient instance to call the API endpoints, as needed.

Essentially, the WebAPI app will run in the same process as your tests, which greatly simplifies debugging.

You'll also probably want to add a 'test' environment configuration file for your application under test (e.g. appsettings.Test.json) and configure the WebApplicationFactory to use the same environment for test runs, so that test runs don't touch your development environment (including the database), and write some code in the 'test app factory' class to re-create/clean the test databases or other stores used in your tests.

Upvotes: 1

Related Questions