How To Unit Test A Public Method That Modifies The State Of Private Member Fields?

Viewed 53

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?

  1. Refactor the class so that the thread and cancellation token are injected constructor dependencies, which can subsequently be mocked.

  2. Add a property IsRunning to allow testing feature that the hosted service is started or stopped

  3. Do not unit test the StopAsync method

0 Answers
Related