chris R
chris R

Reputation: 11

Unit test case for SaveChangesAsync

I am using Mass Transit, Entity Framework, C# in my project.

I have my consumer consuming an event and which insert data in to the table. I would like to know how to mock the consumer and unit test case for this method.

public async Task Consume(ConsumeContext<MyEvent> context)
{
    private readonly MyDbContext _dbContext;  

    try
    {
        // Here logic to insert record in to new database
        var data = new MyService.TableNmae()
        {
            
            Id = context.Message.MyId,
            Description = "test data"
        };

        _ = _dbContext.TableName.AddAsync(data);
        _ = _dbContext.SaveChangesAsync(context.CancellationToken);
    }
    catch (Exception ex)
    {
        _logger.LogCritical($"{GetType().Name}:{nameof(Consume)} {ex}");
    }

    await Task.CompletedTask;
}

Here is my unit test case code i have added

{ private ITestHarness _testHarness;

[SetUp]
public void Initialize()
{
    var serviceCollection = new ServiceCollection();

    serviceCollection.AddMassTransitTestHarness(busRegistrationConfigurator =>
    {
        busRegistrationConfigurator.AddConsumer<MyConsumer>();
    });

    var serviceProvider = serviceCollection.BuildServiceProvider();

    _testHarness = serviceProvider.GetRequiredService<ITestHarness>();
}


[Test]

public async Task TestMethod1()
{
    await _testHarness.Start();
    await _testHarness.Bus.Publish(new MyEvent { Code = "H"});

    Assert.That(await _testHarness.Published.Any<MyEvent>(), Is.True);
    Assert.That(await _testHarness.Consumed.Any<MyEvent>(), Is.True);
}

}

Expected: True But was: False.

Here the first assert is true but second assert always false,

Upvotes: 0

Views: 385

Answers (1)

Chris Patterson
Chris Patterson

Reputation: 33298

Instead of trying to mock ConsumeContext<T>, I recommend using the MassTransit test harness, which is documented on the web site.

As others have pointed out, testing simply that your entity was saved is a pretty trivial test, and more of an integration test assuming you are verifying that the entity was saving all required properties, etc. Not something I would test in isolation, vs. ensuring the data is available for higher level operations being tested.

Upvotes: 1

Related Questions