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,