I am trying to unit test the following method for a class that implements IHostedService interface.
public async Task StopAsync(CancellationToken cancellationToken)
{
await Task.Run(() =>
{
_cancellationTokenSource.Cancel();
_pollLoopThread.Join();
});
}
Currently, the CancellationTokenSource and Thread fields are private.
In such circumstances how could I unit test this method?
Refactor the class so that the thread and cancellation token are injected constructor dependencies, which can subsequently be mocked.
Add a property
IsRunningto allow testing feature that the hosted service is started or stoppedDo not unit test the
StopAsyncmethod