Jake
Jake

Reputation: 53

NServiceBus unit testing: ExpectSend not fulfilled when bus.Send()

I'm using NServiceBus5.2.21, NServiceBus.Testing5.2.1, Moq4.0.1, NUnit3.2.0

Problem: ExpectSend<> keeps failing with

"ExpectedSendInvocation not fulfilled"

when _bus.Send() is called correctly. Not sure what I'm missing here.

Test:

[TestFixture]
public class GeneralLedgerHanlderTest
{
    private Mock<ISendGeneralLedgerToSap> _toSapMock;

    [SetUp]
    public void Setup()
    {
        _toSapMock = new Mock<ISendGeneralLedgerToSap>();
        _toSapMock.Setup(x => x.SendSoapMessageToSap(It.IsAny<GeneralLedgerSapCommand>()));
    }

    [Test]
    public void HandlerMustSendAuditLog()
    {
       NServiceBus.Testing.Test.Handler(bus => new GeneralLedgerToSapHandler(bus, _toSapMock.Object))
            .ExpectSend<GeneralLedgerAuditCommand>(command => command.SagaReferenceId == "ab")
            .OnMessage(new GeneralLedgerSapCommand { SagaReferenceId = "ab" });
    }
}

Handler:

public class GeneralLedgerToSapHandler : IHandleMessages<GeneralLedgerSapCommand>
{
    private readonly IBus _bus;
    private readonly ISendGeneralLedgerToSap _sendSoapToSap;

    public GeneralLedgerToSapHandler(IBus bus, ISendGeneralLedgerToSap sendSoapToSap)
    {
        _bus = bus;
        _sendSoapToSap = sendSoapToSap;
    }

    public void Handle(GeneralLedgerSapCommand message)
    {
        _sendSoapToSap.SendSoapMessageToSap(message);

        var goodsReceiptAuditCommand = new GeneralLedgerAuditCommand
        {
            SagaReferenceId = message.SagaReferenceId,
        };

        _bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);
    }
}

Upvotes: 1

Views: 424

Answers (1)

Sabacc
Sabacc

Reputation: 789

This is a bit tricky to figure out, but the problem arises due to your usage of send:

_bus.Send(EndPointName.SpmAuditLogService, goodsReceiptAuditCommand);

You are sending to a specific destination (I'd recommend to rely on routing instead).

The testing framework has a specific "Expect" option for sends to specific destination. Your test should work correctly if you use ExpectSendToDestination instead:

.ExpectSendToDestination<GeneralLedgerAuditCommand>((command, destination) => command.SagaReferenceId == "ab")

In NServiceBus.Testing v6 (relying on NServiceBus v6), this has been fixed and ExpectSend will also be invoked when sending to a specific destination.

edit: I raised an issue in NServiceBus.Testing about this confusing behavior, see https://github.com/Particular/NServiceBus.Testing/issues/122

Upvotes: 2

Related Questions