I have a method that is started in a new task when the application starts up, and stops when it ends. The method performs some logic every half a second. I am so lost on how I should test it - any leads?
public async Task StartPoll(CancellationToken token)
{
while(!token.IsCancellationRequested)
{
try
{
var dict = dependecy.getDictionary();
var model = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(dict));
udpDistributer.Send(model, model.Length, _distributionEndPoint);
}
finally
{
await Task.Delay(500, Token);
}
}
}
where udpDistributer
is a new UdpClient(0)
that comes from DI and _distributionEndPoint
is an IPEndPoint
Basically I want to check that the logic works and that the right data is sent at the proper interval. How can I do this using xunit?
EDIT
I have gotten as far as this:
// arrange
...
cts = new CancellationTokenSource(timeout);
//act
await sut.StartPoll(cts.Token);
// assert
mockUdpDistributer.Verify(x => x.Send(expectedModel, expectedModel.length,
It.IsAny<IPEndPoint>()), Times.Exactly(expectedTimes));
However, this causes the test to fail with a TaskCanceledException