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));
}