4

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??

1
  • Well spent a time on it , but no success...and there was no help from here too..so finally changed the code to pass the HttpClient to the controller through the dependency injection. It worked fine as expected. Commented Apr 30, 2017 at 20:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have a similiar issue, can you help me please ???stackoverflow.com/questions/78720994/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.