C#C
C#3y ago
LazyGuard

How to test this code?

I am trying to refactor some code in a background service that looks like this:

public class MyBackgroundService : BackgroundService {
    public MyBackgroundService(IKafkaConsumer consumer, IOptionMonithor<WorkerConfig> config, NotificationSender sender) 
    {
        _consumer = consumer;
        _config = config;
        _sender = sender;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) 
    {
        while(!stoppingToken.IsCancellationRequested) 
        {
            await ConsumeKafkaAndSendNotificationAsync();
            await Task.Delay(TimeSpan.FromMilliseconds(_config.CurrentValue.Delay), stoppingToken);
        }
    }
    
    private async Task ConsumeKafkaAndSendNotificationAsyncc()
    {
        var timer = new StopWatch();
        timer.Start();
        Message? message;
        do 
        {
           message  = _consumer.ConsumeMessage(); 
          // .....
          // do some work here on the message
          // .....
           await _sender.SendNotificationAsync(message);
        } while (
            message != null && timer.Elapsed < TimeSpan.FromMilliseconds(_config.CurrentValue.Delay)
        )
    }
}


Complex work should usually be kept somewhere else outside of the loop of the backgroundService. However, things get hairy enough that some tests will help.
Was this page helpful?