0

How to write unit test case for a method which doesnot return anything.

My masstransit consumer just insert data to database

public async Task Consume(ConsumeContext<CreateEvent> context)
{
    var existing = await _dbContext.Mytable.SingleOrDefaultAsync(c => c.Id.Equals(context.Message.Id));
    if (existing == null)
    {
        var newData = new Table
        {
            Id = context.Message.Id,       
            Description = context.Message.Description,
        };
        await _dbContext.table.AddAsync(newData);
        await _dbContext.SaveChangesAsync();
    }
    _logger.LogInformation($"{context.Message.Id.ToUpperInvariant()} already exists.");
    await Task.CompletedTask;
}

What needs to be covered as part of unit test case here?

Assert.That(await harness.Published.Any<CreateEvent>(), Is.True);

dbContext.Setup(r => r.Table).ReturnsDbSet(mysampleEntities);
dbContext.Setup(r => r.SaveChangesAsync(It.IsAny<CancellationToken>())).ReturnsAsync(1).Verifiable();

dbContext.Verify();  // this gives me error "This mock failed"

Now I am just checking this event is published.

await Task.CompletedTask; - how to write unit test case for task.completedtask
Chris Patterson
  • 28,659
  • 3
  • 47
  • 59
jubi
  • 569
  • 1
  • 10
  • 34
  • See https://stackoverflow.com/questions/246038/unit-testing-void-methods – jao Feb 14 '23 at 14:38
  • 1
    You need to verify that your data in the database was saved appropriately. – MakePeaceGreatAgain Feb 14 '23 at 14:41
  • @MakePeaceGreatAgain Thant gives me error This mock failed verification due to the following error – jubi Feb 14 '23 at 14:51
  • You should test your method like @MakePeaceGreatAgain said, but that's a matter for a new question now. You can add a new question (or find existing questions) specifically asking about mocking `DbContext` in your test methods. – Orion Feb 14 '23 at 14:58
  • @Orion i have that failure case added in my question – jubi Feb 14 '23 at 15:05
  • 1
    Sure, but this is no longer a question about "How to write unit test case for a masstransit consumer which doesnot return anything", it's a question about mocking a DbContext in a unit test, so you should either edit the question or post a new one. It will give your question more visibility and accuracy. – Orion Feb 14 '23 at 15:13
  • perfect, i will post new one – jubi Feb 15 '23 at 05:55

0 Answers0