6

In NSubstitute, is it possible to specify a message that should be thrown if a Received fails? Something like the following:

[Test]
public void Should_execute_command()
{
    var command = Substitute.For<ICommand>();
    var something = new SomethingThatNeedsACommand(command);

    something.DoSomething();

    command.Received()
        .Execute()
        .Because("We should have executed the command that was passed in");
}

For comparison, in Moq, you can do this:

command.Verify(c => c.Execute, "We should have executed the command that was passed in");

And then you get that message as part of the test failure message in your test runner. This can help to make test failures easier to read/diagnose. Is there anything similar in NSubstitute?

Liam
  • 27,717
  • 28
  • 128
  • 190
eliah
  • 2,267
  • 1
  • 21
  • 23

1 Answers1

4

There is no way to change the message that you receive in the ReceivedCallException; it is built directly from hard-coded strings in the NSubstitute.Core.ReceivedCallsExceptionThrower Throw method:

public void Throw(ICallSpecification callSpecification, IEnumerable<ICall> matchingCalls, IEnumerable<ICall> nonMatchingCalls, Quantity requiredQuantity)
{
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.AppendLine(string.Format("Expected to receive {0} matching:\n\t{1}", requiredQuantity.Describe("call", "calls"), callSpecification));
    this.AppendMatchingCalls(callSpecification, matchingCalls, stringBuilder);
    if (requiredQuantity.RequiresMoreThan<ICall>(matchingCalls))
    {
        this.AppendNonMatchingCalls(callSpecification, nonMatchingCalls, stringBuilder);
    }
    throw new ReceivedCallsException(stringBuilder.ToString());
}

Unless you're ready to dive in NSubstitute code, for now the best bet would to catch the ReceivedCallsException and throw your own message.

samy
  • 14,832
  • 2
  • 54
  • 82