Search code examples
c#windows-servicesxunitworker-service

Expected worker.ExecuteTask.IsCanceled to be true, but found False


I create a worker service project. also, add a unit test project ( xunit ). this unit test failed each and every time. enter image description here

    [Fact]
    public async Task ShouldCancelWorker()
    {
        CancellationTokenSource source = new CancellationTokenSource();
        CancellationToken token = source.Token;
        await worker.StartAsync(token);

        source.Cancel();

        worker.ExecuteTask.IsCanceled.Should().BeTrue();
    }

it always returns true any idea how to solve this issue


Solution

  • I assume that you your logic for checking the token that is canceled ( token.IsCancellationRequested) is correct. In that case you should put a delay between source.Cancel() and worker.ExecuteTask.IsCanceled.Should().BeTrue() in order to be able a pass one iteration in the worker execution loop.