Mocking IEndpointInstance with NSubstitute

Hi,

I’,m trying to mock IEndpointinstance with NSubstitute to test what was actually sent, but I get an System.ArgumentNullException. Using IBus in similar way works fine.

This is the code:

var endpointInstance = Substitute.For<IEndpointInstance>();
var myService = new MyService(endpointInstance);
myService.DoSomething(myObject);        // this calls IEndpointInstance.Send(....)     
endpointInstance.Received().Send(Arg.Any<MyMessage>());

This throws this exception, (and no, mye message object is not null):

System.ArgumentNullException : Value cannot be null.
    Parameter name: message
       at NServiceBus.IMessageSessionExtensions.Send(IMessageSession session, Object message) in C:\BuildAgent\work\3206e2123f54fce4\src\NServiceBus.Core\IMessageSessionExtensions.cs:line 19

Is this by design? Reading the last comment from this SO-topic it seems tho be working with Moq, so I was wondering whether there is an issue with NSubstitute.

Note: I have refactored the code to use TestableEndpointInstance instead, and that works fine.

Hi, Ivan,

The exception comes from an extension method that provides the send functionality https://github.com/Particular/NServiceBus/blob/develop/src/NServiceBus.Core/IMessageSessionExtensions.cs#L16

Based on that it looks like your service passes null to the endpoint instance. Maybe one of your substitutes returns null that is then passed into the endpoint instance send method?

Maybe it is a bit simpler to use our NServiceBus.Testing package? Have a look at some of the examples here Unit Testing NServiceBus • Testing Samples • Particular Docs. The library provides a TestableMessageSession that could fulfill your needs

Regards
daniel

Hi Daniel,

A, it is an extension indeed, and mocking static methods is not the easiest part https://stackoverflow.com/questions/5864076/mocking-static-methods.

Without digging dipper in v5, I suppose the send was not an extension on IBus, which explains why it was possible mock it and test on the send .

Yep, I have refactored the tests to use NServiceBus.Testing and TestableEndpointInstance.

Thank you