0

In order to create the test harness for the SubmitOrderConsumer, I will have to build a ServiceCollection containing all the depdencies of SubmitOrderConsumer.

Mock<INotifier> mockNotifier = new Mock<INotifier>();
Mock<IStockChecker> mockStockChecker = new Mock<IStockChecker>();
Mock<IFidelityUpdater> mockFidelityUpdater = new Mock<IFidelityUpdater>();
Mock<IPromotionManager> mockPromotionManager = new Mock<IPromotionManager>();
await using var provider = new ServiceCollection()
    .AddMassTransitTestHarness(cfg =>
    {
        cfg.AddConsumer<SubmitOrderConsumer>();
    })
    .AddSingleton<INotifier>(mockNotifier.Object)
    .AddSingleton<IStockChecker>(mockStockChecker.Object)
    .AddSingleton<IFidelityUpdater>(mockFidelityUpdater.Object)
    .AddSingleton<IPromotionManager>(mockPromotionManager.Object)
    ..
    .BuildServiceProvider(true);ds

var harness = provider.GetRequiredService<ITestHarness>();
...
mockNotifier.Verify(...)

The Moq.Automock library helps me to create the SubmitOrderConsumer and auto-mock all its depdencies so the above codes is reduced to

AutoMocker mocker = new AutoMocker();
await using var provider = new ServiceCollection()
    .AddMassTransitTestHarness(cfg =>
    {
        cfg.AddConsumer<SubmitOrderConsumer>();
    })
    .AddSingleton(mocker.CreateInstance<SubmitOrderConsumer>())
    .BuildServiceProvider(true);

var harness = provider.GetRequiredService<ITestHarness>();
...
mocker.GetMock<INotifier>().Verify(...)

Question:

The class AutoMocker is also a IServiceProvider, so the above codes have 2 IServiceProvider:

  • the first IServiceProvider is the mocker which can resolve the SubmitOrderConsumer
  • the second IServiceProvider is the provider which can resolve the ITestHarness

is it possible to create the ITestHarness with my mocker IServiceProvider? something like

ITestHarness harness = new ContainerTestHarness(mocker);
Hiep
  • 2,483
  • 1
  • 25
  • 32
  • Never used auto mocker, not a clue. Good luck. – Chris Patterson Aug 07 '22 at 12:47
  • I didn't find out if it is possible to create the test harness "manually" (without the help of a ServiceCollection). For now, I will just use 2 ServiceProvider, just hiding one in the "StartTestHarnessFor" function https://gist.github.com/duongphuhiep/15f223437bfd88a05de09c420473133b – Hiep Aug 08 '22 at 06:04

0 Answers0