Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient connection issue to WebAPI hosted using Asp.NetCore TestServer

In the unit Test cases, TestServer is used for in-memory hosting of the WebAPI. After this, we are trying to make HttpConnection to this hosted WebAPI using some code like this:

HttpClient client= new HttpClient();
client.BaseAddress("url");
client.GetAsync("url").Result();

This code gives an exception, with the error message

"Connection refused".

But if we get the HttpClient object using the below code and follow the above steps, it works fine.

TestServer.CreateClient() 

What could be the reason behind it? Is it because it's an in-memory hosted WebAPI? No actual Http context is there??

like image 597
Munish Avatar asked Apr 18 '26 12:04

Munish


1 Answers

That's by design. When you call TestServer.CreateClient() a client with special HttpMessageHandler is created. That handler allows to directly call APIs under test without exposing it as HTTP server:

public class TestServer : IServer, IDisposable
{
    public HttpClient CreateClient()
    {
        HttpClient httpClient = new HttpClient(this.CreateHandler());
        ...
    }
}

That should be faster and suitable enough for unit-testing. For integration testing, run a Kestrel server at test startup.

P.S. I hope your application design became better with DI instead of explicit building. That's nice you resolved the problem this way.

like image 181
Ilya Chumakov Avatar answered Apr 20 '26 00:04

Ilya Chumakov