0

I'm trying to test a method that has an async method call to a restful API inside. The implementation should throw an exception after X seconds if the request to the API does not have any result. I have found a pretty useful extension method for throwing a TimoutException by Lawrence Johnston in this article.

Here is a short snippet of my implementation:

public async Task MyMethod()
{
    // _httpAdapter is a wrapper class that uses HttpClient
    var response = await _httpAdapter.PostAsync(new Uri("https://myapi.de/"), data)
                      .TimeoutAfter(10000);

    //... (do some stuff and return the result)
}

At the moment my method is not throwing any exceptions.

I'm trying to test this method like this over NSubstitute:

[Test]
public void MyMethod_HttpClientAdapterPostAsyncTimeout_IsError()
{
    // --------------------------------------------------------------------------------
    // PREPARE
    // --------------------------------------------------------------------------------
    // ...
    _httpAdapter.When(x => x.PostAsync(Arg.Any<Uri>(), Arg.Any<HttpContent>()))
                        .Do(x => Task.Delay(11000));

    // --------------------------------------------------------------------------------
    // SYSTEM UNDER TEST
    // --------------------------------------------------------------------------------
    void call() => handler.MyMethod().Wait();

    // --------------------------------------------------------------------------------
    // VERIFY
    // --------------------------------------------------------------------------------
    Assert.That(call, Throws.Exception.InstanceOf<TimeoutException>()
                .With.Message.EqualTo(Constants.ErrorMessage_Avp_RequestFailed));
}
  • For testing async methods you need async tests. I don't see any `async` (modifiers or suffixes) in your test. – Sinatr Jul 20 '20 at 09:58
  • I am using the [Task.Wait](https://learn.microsoft.com/de-de/dotnet/api/system.threading.tasks.task.wait?view=netcore-3.1) method to wait until the task completes the execution. I dont understand why I cant use this method. – Christopher Jul 20 '20 at 11:03
  • I suggest you to read [msdn](https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/november/async-programming-unit-testing-asynchronous-code) and topics like [this one](https://stackoverflow.com/q/7340309/1997232). – Sinatr Jul 20 '20 at 11:10
  • 1
    [Task.wait() can easily cause deadlocks](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html) – JonasH Jul 20 '20 at 11:35

0 Answers0