简体   繁体   中英

How can I specify a failure message for an NSubstitute .Received call?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM