Search code examples
c#unit-testingnservicebus

NServiceBus: Testing that event is published AND exception is thrown at the same time


I ran across some code in one of our services that looks like this:

try
{
    // Step 1: collect underpants.
}
catch (Exception ex)
{
    // If this is the last retry we'll raise an event.
    if (Bus.IsLastRetry())
    {
        PublishFailedEvent(ex);
    }

    // But we'll also send the error to the error queue no matter what.
    throw;
}

And a test that looks like this:

Test.Handler(bus => new Processor() { Bus = bus })
    .ExpectPublish<IFailedEvent>()
    .OnMessage<ISomeHappenedEvent>();

Because we are throwing right after publishing the test fails. Is there a way to test that the FailedEvent is published AND the exception is thrown?


Solution

  • Just wrap the call to Test() in a try catch and then assert against the exception. Depending on the version of NSB, the handler may raise a TargetInvocationException, which you'll need to interrogate to get to the inner exception.

    try
    {
        Test.Handler(bus => new Processor() { Bus = bus }).OnMessage<ISomeHappenedEvent>();
    }
    catch (MyExpectedException ex)
    {
        // Asserts 
        ...
    }
    

    or,

    try
    {
        Test.Handler(bus => new Processor() { Bus = bus }).OnMessage<ISomeHappenedEvent>();
    }
    catch (TargetInvocationException ex)
    {
        // Asserts against ex.InnerException
        ...
    }