Unit test does not pass for C# .NET Core Worker Service project ScheduledWorkerService class that inherits from IHostedService

The worker service project has ScheduledWorkerService class that inherits from IHostedService.

Here’s a unit test for it:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class ScheduledWorkerService(ILogger<ScheduledWorkerService> logger,
EmailServiceParallel emailServiceParallel,
IOptions<Settings> Settings) : IHostedService, IDisposable
{
private Settings _Settings = Settings.Value;
public async Task StartAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Service started. Running loop...");
while (!stoppingToken.IsCancellationRequested)
{
try
{
logger.LogInformation("Worker service triggering background task at: {time}", DateTimeOffset.Now);
await emailServiceParallel.RunBackgroundTaskAsync(stoppingToken);
}
catch (Exception ex)
{
var exceptionMsg = string.Format("WorkerService: StartAsync There is an exception {0}, {1}", DateTime.Now, ex.Message);
logger.LogError(ex,exceptionMsg);
}
// Define your desired loop interval here (e.g., 5 minutes)
await Task.Delay(_Settings.IntervalInMinutes, stoppingToken);
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Worker service is stopping at: {time}", DateTimeOffset.Now);
return Task.CompletedTask;
}
}
</code>
<code>public class ScheduledWorkerService(ILogger<ScheduledWorkerService> logger, EmailServiceParallel emailServiceParallel, IOptions<Settings> Settings) : IHostedService, IDisposable { private Settings _Settings = Settings.Value; public async Task StartAsync(CancellationToken stoppingToken) { logger.LogInformation("Service started. Running loop..."); while (!stoppingToken.IsCancellationRequested) { try { logger.LogInformation("Worker service triggering background task at: {time}", DateTimeOffset.Now); await emailServiceParallel.RunBackgroundTaskAsync(stoppingToken); } catch (Exception ex) { var exceptionMsg = string.Format("WorkerService: StartAsync There is an exception {0}, {1}", DateTime.Now, ex.Message); logger.LogError(ex,exceptionMsg); } // Define your desired loop interval here (e.g., 5 minutes) await Task.Delay(_Settings.IntervalInMinutes, stoppingToken); } } public Task StopAsync(CancellationToken cancellationToken) { logger.LogInformation("Worker service is stopping at: {time}", DateTimeOffset.Now); return Task.CompletedTask; } } </code>
public class ScheduledWorkerService(ILogger<ScheduledWorkerService> logger,
        EmailServiceParallel emailServiceParallel,
        IOptions<Settings> Settings) : IHostedService, IDisposable
{
    private Settings _Settings = Settings.Value;

    public async Task StartAsync(CancellationToken stoppingToken)
    {
        logger.LogInformation("Service started. Running loop...");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                logger.LogInformation("Worker service triggering background task at: {time}", DateTimeOffset.Now);
                await emailServiceParallel.RunBackgroundTaskAsync(stoppingToken);
            }
            catch (Exception ex)
            {
                var exceptionMsg = string.Format("WorkerService: StartAsync There is an exception  {0}, {1}", DateTime.Now, ex.Message);
                logger.LogError(ex,exceptionMsg);
            }

            // Define your desired loop interval here (e.g., 5 minutes)
            await Task.Delay(_Settings.IntervalInMinutes, stoppingToken);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        logger.LogInformation("Worker service is stopping at: {time}", DateTimeOffset.Now);

        return Task.CompletedTask;
    }
}

Please find the unit test. The unit throw exception for StartAsync on

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>_reliaVoteBackgroundEmailServiceParallel.Verify(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()), Times.Once);
</code>
<code>_reliaVoteBackgroundEmailServiceParallel.Verify(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()), Times.Once); </code>
_reliaVoteBackgroundEmailServiceParallel.Verify(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()), Times.Once);

I added Task.Run since start method has while loop and try to assert inside. The unit test flow happens properly but the verify could not be done. Found since cancellation cause task to cancel and could not verify. Moved assertion before cancellation. The execution is not able to go to next statement from verify. The test continue to run. Cancel token is not execute.

So added the try catch and in the catch checking the message if it is task cancelled return ie assuming test execution is right. StopAsync unit test just assert the this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Assert.True(ReferenceEquals(stopAsync, Task.CompletedTask));
</code>
<code>Assert.True(ReferenceEquals(stopAsync, Task.CompletedTask)); </code>
Assert.True(ReferenceEquals(stopAsync, Task.CompletedTask));

If I try to verify logger.LogInformation is not working. Please find the commented code.

Please advise StartAsync_StartsTimerAndLogs_Test is anything I can assert similarly in StopAsync.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class ScheduledWorkerServiceTest : ScheduledWorkerServiceFixture
{
[Fact]
public async Task StartAsync_StartsTimerAndLogs_Test()
{
try
{
// Arrange
var mockTaskDelay = new Mock<Func<int, CancellationToken, Task>>(); // Mock Task.Delay
var cancellationTokenSource = new CancellationTokenSource();
_EmailServiceParallel.Setup(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var scheduledWorker = new ScheduledWorkerService(_mockLogger.Object, _EmailServiceParallel.Object, _mockOptions);
// Simulate delay and cancellation after some time (adjust delay)
Task.Run(async () =>
{
await Task.Delay(5000); // Replace with your desired delay
cancellationTokenSource.Cancel();
_mockLogger.Verify(m => m.LogInformation("Service started. Running loop..."));
_EmailServiceParallel.Verify(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()), Times.Once);
});
// Act
var startTask = scheduledWorker.StartAsync(cancellationTokenSource.Token);
// Await both tasks (might throw TaskCanceledException)
await Task.WhenAll(startTask);
// cancellationTokenSource.Cancel(); // Simulate cancellation
// Assert
}
catch (Exception ex) {
if (ex.Message == "A task was canceled") {
return;
}
}
}
[Fact]
public void StopAsync_StopsTimerAndLogs_Test()
{
// Arrange
var cancellationTokenSource = new CancellationTokenSource();
// Act
var scheduledWorker = new ScheduledWorkerService(_mockLogger.Object, _EmailServiceParallel.Object, _mockOptions);
var stopAsync = scheduledWorker.StopAsync(cancellationTokenSource.Token);
// Assert
// Ensure the returned task is Task.CompletedTask
Assert.True(ReferenceEquals(stopAsync, Task.CompletedTask));
// _mockLogger.Verify(m => m.LogInformation(It.IsAny<string>()), Times.Once);
// Additionally, you can assert that the message contains the specific text
/// Assert.Contains("Worker service is stopping at:", _mockLogger.Invocations.Last().Arguments.First().ToString());
// _mockLogger.Verify(m => m.LogInformation("Worker service is stopping at: {time}", It.IsAny<DateTimeOffset>()), Times.Once);
//_mockLogger.Verify(m => m.LogInformation("Scheduled worker is stopping..."));
}
}
</code>
<code>public class ScheduledWorkerServiceTest : ScheduledWorkerServiceFixture { [Fact] public async Task StartAsync_StartsTimerAndLogs_Test() { try { // Arrange var mockTaskDelay = new Mock<Func<int, CancellationToken, Task>>(); // Mock Task.Delay var cancellationTokenSource = new CancellationTokenSource(); _EmailServiceParallel.Setup(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>())) .Returns(Task.CompletedTask); var scheduledWorker = new ScheduledWorkerService(_mockLogger.Object, _EmailServiceParallel.Object, _mockOptions); // Simulate delay and cancellation after some time (adjust delay) Task.Run(async () => { await Task.Delay(5000); // Replace with your desired delay cancellationTokenSource.Cancel(); _mockLogger.Verify(m => m.LogInformation("Service started. Running loop...")); _EmailServiceParallel.Verify(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()), Times.Once); }); // Act var startTask = scheduledWorker.StartAsync(cancellationTokenSource.Token); // Await both tasks (might throw TaskCanceledException) await Task.WhenAll(startTask); // cancellationTokenSource.Cancel(); // Simulate cancellation // Assert } catch (Exception ex) { if (ex.Message == "A task was canceled") { return; } } } [Fact] public void StopAsync_StopsTimerAndLogs_Test() { // Arrange var cancellationTokenSource = new CancellationTokenSource(); // Act var scheduledWorker = new ScheduledWorkerService(_mockLogger.Object, _EmailServiceParallel.Object, _mockOptions); var stopAsync = scheduledWorker.StopAsync(cancellationTokenSource.Token); // Assert // Ensure the returned task is Task.CompletedTask Assert.True(ReferenceEquals(stopAsync, Task.CompletedTask)); // _mockLogger.Verify(m => m.LogInformation(It.IsAny<string>()), Times.Once); // Additionally, you can assert that the message contains the specific text /// Assert.Contains("Worker service is stopping at:", _mockLogger.Invocations.Last().Arguments.First().ToString()); // _mockLogger.Verify(m => m.LogInformation("Worker service is stopping at: {time}", It.IsAny<DateTimeOffset>()), Times.Once); //_mockLogger.Verify(m => m.LogInformation("Scheduled worker is stopping...")); } } </code>
public class ScheduledWorkerServiceTest : ScheduledWorkerServiceFixture
{
    [Fact]
    public async Task StartAsync_StartsTimerAndLogs_Test()
    {
        try 
        
    {
        // Arrange
        var mockTaskDelay = new Mock<Func<int, CancellationToken, Task>>(); // Mock Task.Delay

        var cancellationTokenSource = new CancellationTokenSource();
        _EmailServiceParallel.Setup(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()))
        .Returns(Task.CompletedTask);

        var scheduledWorker = new ScheduledWorkerService(_mockLogger.Object, _EmailServiceParallel.Object, _mockOptions);

        // Simulate delay and cancellation after some time (adjust delay)
        Task.Run(async () =>
        {
            await Task.Delay(5000); // Replace with your desired delay
            cancellationTokenSource.Cancel();
            _mockLogger.Verify(m => m.LogInformation("Service started. Running loop..."));
            _EmailServiceParallel.Verify(m => m.RunBackgroundTaskAsync(It.IsAny<CancellationToken>()), Times.Once);
        });

        // Act
        var startTask = scheduledWorker.StartAsync(cancellationTokenSource.Token);

        // Await both tasks (might throw TaskCanceledException)
        await Task.WhenAll(startTask);

        // cancellationTokenSource.Cancel(); // Simulate cancellation
        // Assert
        
        }
        catch   (Exception ex) {
           if (ex.Message == "A task was canceled") {
                   return;
               }
           }
    }

    [Fact]
    public void StopAsync_StopsTimerAndLogs_Test()
    {
        // Arrange
        var cancellationTokenSource = new CancellationTokenSource();
        // Act
        var scheduledWorker = new ScheduledWorkerService(_mockLogger.Object, _EmailServiceParallel.Object, _mockOptions);
        var stopAsync = scheduledWorker.StopAsync(cancellationTokenSource.Token);
        // Assert
        // Ensure the returned task is Task.CompletedTask
        Assert.True(ReferenceEquals(stopAsync, Task.CompletedTask));

        // _mockLogger.Verify(m => m.LogInformation(It.IsAny<string>()), Times.Once);
        // Additionally, you can assert that the message contains the specific text
        /// Assert.Contains("Worker service is stopping at:", _mockLogger.Invocations.Last().Arguments.First().ToString());


        // _mockLogger.Verify(m => m.LogInformation("Worker service is stopping at: {time}", It.IsAny<DateTimeOffset>()), Times.Once);
        //_mockLogger.Verify(m => m.LogInformation("Scheduled worker is stopping..."));

    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật