NServiceBus Testing Upgrade Version 5 to 6

Component: Testing

Upgrade to NServiceBus Version 6

NServiceBus.Testing requires NServiceBus Version 6.

As part of upgrading to NServiceBus.Testing Version 6, projects will also require an upgrade to NServiceBus Version 6.

New Unit Testing capabilities

NServiceBus.Testing Version 6 provides an alternative way to write tests using a more traditional Arrange Act Assert pattern. This allows for easier extension and tooling integration. For more details on the new testing capabilities, see the Unit Testing NServiceBus 6 Sample.

Testing Framework

Removed Test.Initialize()

It is no longer required to call Test.Initialize() before executing a test. All calls to Test.Initialize() can be safely removed.

Unobtrusive Message Conventions

With the removal of Test.Initialize() it is also no longer required to configure unobtrusive message conventions.

Testing Message Handlers

ExpectReturn Method

Use ExpectReply instead of ExpectReturn.

SendToSites Methods

ExpectSendToSites and ExpectNotSendToSites methods have been removed from the Testing Framework. Handlers using the Gateway can still be tested using the ExpectSend overload which provides the SendOption:

6.x NServiceBus.Testing
public void ExpectSendToSite()
            check: (message, options) =>
                return options.GetSitesRoutingTo().Contains("myFavouriteSite");
        .OnMessage(new MyMessage());

class MyHandler :
    public Task Handle(MyMessage message, IMessageHandlerContext context)
        var options = new SendOptions();

        return context.Send(new GatewayMessage(), options);

Testing Sagas

Using When

In NServiceBus Versions 6 and above, message handlers have an additional IMessageHandlerContext parameter. This context parameter needs to be provided when defining the method to invoke.

6.x NServiceBus.Testing
    sagaIsInvoked: (saga, context) =>
        return saga.Handle(new StartsSaga(), context);
5.x NServiceBus.Testing
.When(s => s.Handle(new StartsSaga()))

A new overload has been added to simplify this:

6.x NServiceBus.Testing
    handlerSelector: saga =>
        return saga.Handle;
    message: new StartsSaga())
It's important to pass the context provided by the delegate arguments to the handle method.

Configuring a message ID

The message ID can be manually configured using the ConfigureMessageHandler option. See Configuring the context section below for more details.

Configuring the context

Both Saga and Handler tests contain a ConfigureHandlerContext method to enable custom configuration of the IMessageHandlerContext which is passed to the invoked handler methods.

6.x NServiceBus.Testing
    .ConfigureHandlerContext(c =>
        c.MessageId = "my message ID";
    .When(s => s.Handle, new StartsSaga());

Related Articles

Last modified