1

I have 600 functional xUnit tests and each of the test is calling a httpClient.GetAsync(apiUrl) and httpClient.PostAsync(apiUrl, data) methods in the middle of the test which will call some external APIs.

When I execute each test sequentially all working fine. Also even when I run 5 - 6 test cases parallelly then also everything works fine.

My problem is, when I start all 600 test cases from the top (which will start around 50 out 600 test cases parallelly), all the tests are hanging where it sends the httpClient.PostAsync(apiUrl, data) method.

The same issue happened at the point where it executes the httpClient.GetAsync(apiUrl) method. But after I change it as httpClient.GetAsync(apiUrl).ConfigureAwait(false) it fix the issue.

But when I change the httpClient.PostAsync(apiUrl, data) to httpClient.PostAsync(apiUrl, data).ConfigureAwait(false) issue is still the same.

Can someone explain why this happens and what should I do to fix this issue.

Prabodha
  • 520
  • 1
  • 6
  • 19
  • 2
    How HttpClient is injected in actual code? Is HttpClient is static instance or every flow creates a new instance of HttpClient? – user1672994 Jul 07 '22 at 05:11
  • @user1672994, each test case creates its own HttpClient instance. its not a static instance. – Prabodha Jul 07 '22 at 05:42
  • 1
    Is there a chance the service simply won't respond to 600 requests at once? (e.g. because of DoS protection, or rate limiting, or because it can't handle it performance-wise) – John Wu Jul 07 '22 at 06:04
  • @JohnWu, No its not sending any responses nor throwing any exceptions. I've set few console logs to check the execution path. After it hits the httpClient.PostAsync() method, it just hangs there forever. – Prabodha Jul 07 '22 at 06:55
  • do you await this tasks? – d00lar Jul 07 '22 at 07:43
  • It seems the issue is with you using 500 httpclient instances. Can't you create one instance and let that handle all your test cases? – CthenB Jul 07 '22 at 08:22
  • `HttpClient` is thread-safe, it makes sense to inject it in order to cut down on the number of sockets – Charlieface Jul 07 '22 at 09:49
  • @d00lar, Yes I await the task. – Prabodha Jul 07 '22 at 10:23

1 Answers1

0

When I change the httpClient.PostAsync(apiUrl, data) method as below, it fix the issue. I'm not sure what the difference between two methods.

Previous way

var response = await httpClient.PostAsync(apiUrl, data);

I modified above as below and it fixed the issue.

var task = httpClient.PostAsync(apiUrl, data);
var response = task.GetAwaiter().GetResult();

Also I found some similar problem that has been discussed in below post. If someone facing similar issue, please follow below post as it contains some more useful tips and reasons. HttpClient.GetAsync(...) never returns when using await/async

Prabodha
  • 520
  • 1
  • 6
  • 19