4

I'm trying to figure out whether it's possible to use custom HTTP client in integration tests?

Instead of getting client instance from TestServer

Client = Server.CreateClient() 

to use my own implementation. Smthng like:

Client = new DSClient(Server.BaseAddress.AbsoluteUri, Credential);

When I do so i'm constantly getting 404. WAIDW?

7
  • Are you calling the base constructor in your inherited class? Commented Feb 27, 2017 at 8:14
  • @john Nope. The point is my Client is a wrapper and it doesn't provide same methods as HttpClient Commented Feb 27, 2017 at 8:24
  • 2
    If Server.CreateClient() is part of the self-hosting functionality, then you'll need to pass it as the base HttpClient into your wrapper. The self-hosting functionality operates entirely in memory, I believe. Commented Feb 27, 2017 at 8:25
  • Obviously that doesn't mean that you need to expose the same methods as the client provided, but I think you have to use it in your wrapper methods. Whare are you trying to achieve? Could it be done by creating your own DelegatingHandler? Commented Feb 27, 2017 at 8:28
  • 3
    @john yep, you saved me. Server = new TestServer(webHostBuilder); TestClient = Server.CreateClient(); Client = new DSClient(TestClient); Had to modify DSClient class with new constructor, but it works. Thanks Commented Feb 27, 2017 at 15:54

1 Answer 1

2

I faced the same problem and in my situation I can not use the existing HttpClient because I need to modify the HttpClient when initializing it. So my solution is to create a server and test it using my own HttpClient.

using(var server = WebHost.CreateDefaultBuilder(new List<string>().ToArray())
    .UseEnvironment("Test")
    .UseStartup<Startup>()
    .UseKestrel(options =>
    {
        options.Listen(IPAddress.Loopback, 5000);
    })
.Build())
{
    server.Start();
    var client = new HttpClient
    {
        BaseAddress = new Uri("http://localhost:5000")
    }
    var resp = client.GetAsync("test/testme").Result;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Will this work with https assuming that tests are running under non-priviledged account?
Yes, it should work. Binding port 443 doesn't require elevation, at least on Windows. All you need a (self-signed) SSL certificate in the current user's store.

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.