Reputation: 59
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??
Upvotes: 4
Views: 1220
Reputation: 25019
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.
Upvotes: 1