Search code examples
testingdependency-injectionnservicebusnservicebus-sagas

Dependency injection for NServiceBus Saga unit testing


My question is similar to question about DI for NserviceBus Handler for testing (Handler). As a solution, you can use constructor injection by using the following syntax:

Test.Handler<YourMessageHandler>(bus => new YourMessageHandler(dep1, dep2))

I couldn't find a way to use the same approach for Saga testing. There is a support for property injecting, which would look something like this:

var saga = Test.Saga<MySaga>()
            .WithExternalDependencies(DependenciesSetUp);
private void DependenciesSetUp(MySaga saga)
    {
        saga.M2IntegrationService = M2IntegrationService.Object;
        saga.ProcessLogService = ProcessLogService.Object;
        saga.Log = Log.Object;
    }

However, this approach requires making my dependencies public properties. And I want to try to avoid it.

Is there a way to use construction dependency injection for Saga testing?


Solution

  • You can work around this like:

    Have a saga that has a constructor with parameters (in addition to a default empty constructor, which is required).

    This is how your test can look like:

    Test.Initialize();
    var injected = new InjectedDependency() {Id = Guid.NewGuid(), SomeText = "Text"};
    var testingSaga = new MySaga(injected);
    var saga = Test.Saga(testingSaga);
    saga.WhenReceivesMessageFrom("enter code here")
    

    Will this work for you?