I wrote a blog about replacing the timeout based test harness with a semaphore driven one here. This made things much more robust when you want blackbox type testing, fire a number of events and wait until all have been digested and their spawned child events are digested.
This worked well and robust. But it still used the Masstransit harness for hosting. This made the InMemory bus more than twice as slow as hosting Masstransit in a service, including database I/O so probably a lot slower when only looking at bus performance.
But it’s pretty easy hosting Masstransit from a none service project like a test project. Instead of configuring with AddMassTransitTestHarness use the standard AddMasstransit extension method. Now events will not be consumed when you publish them, this is because the IHostedService haven’t been started. So that’s an easy fix. If we base the code on the IHarness from my previous blog post.
public Harness(IEnumerable<IHostedService> services) { _services = services; } public async Task Start() { var source = new CancellationTokenSource(); foreach (var service in _services) await service.StartAsync(source.Token); } public async Task Stop() { var source = new CancellationTokenSource(); foreach (var service in _services) await service.StopAsync(source.Token); }
Call Start from your test setup and stop from your test teardown. This will start the background workers for Masstransit and make sure it listens and consumes events. The service will not work unless you add logging to your IoC config.
new ServiceCollection() .AddLogging();
Coupled with the harness-code from previous blog post you now have a very robust and fast test harness. Full code below
(more…)