I'm recently learning and using Polly to add resilience to my code, especially for the timeout and retry policies. However, I don't know how to unit test the code with polly. To be more specific, I don't know how to mock a method with Cancellation Token as its parameter. Below is the structure of my code
public class Caller
{
private IHttpManager httpManager;
private IAsyncPolicy<HttpResponseMessage> policyWrap;
public Caller(IHttpManager httpManager, IAsyncPolicy<HttpResponseMessage> policyWrap)
{
this.httpManager= httpManager;
this.policyWrap = policyWrap;
}
public async Task CallThirdParty()
{
HttpResponseMessage httpResponse = await policyWrap.ExecuteAsync(async ct => await httpManager.TryCallThirdParty(ct), CancellationToken.None);
}
}
public interface IHttpManager
{
Task<HttpResponseMessage> TryCallThirdParty(CancellationToken cancellationToken);
}
Below is the unit test I intend to run but don't know how.
[Test]
public void TestBehaviourUnderTimeoutPolicy()
{
// Set up the timeout policy such that the governed delegate will terminate after 1 sec if no response returned
AsyncTimeoutPolicy<HttpResponseMessage> timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(1, TimeoutStrategy.Optimistic);
// mock IHttpManager
var mockHttpManager= new Mock<IHttpManager>();
// THIS IS WHERE I'M HAVING TROUBLE WITH.
// I want to simulate the behaviour of the method such that
// it will throw an exception whenever the CancellationToken passed from the polly caller expires
// But how can I do that with mock?
mockHttpManager.Setup(m => m.TryCallThirdParty(It.IsAny<CancellationToken>()))).Returns(Task.Run(() => { Thread.Sleep(10000); return new HttpResponseMessage(); }));
Caller c = new Caller(mockHttpManager.Object, timeoutPolicy);
await c.CallThirdParty();
}