Reputation: 841
The worker service project has ScheduledWorkerService
class that inherits from IHostedService
.
Here's a unit test for it:
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
_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
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
.
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..."));
}
}
Upvotes: 0
Views: 34