如何为 NSubstitute .Received 调用指定失败消息?

eli*_*iah 7 c# nsubstitute

在 NSubstitute 中,是否可以指定在 Received 失败时应抛出的消息?像下面这样:

[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");
}
Run Code Online (Sandbox Code Playgroud)

为了进行比较,在 Moq 中,您可以这样做:

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

然后您会收到该消息作为测试运行程序中测试失败消息的一部分。这有助于使测试失败更容易阅读/诊断。NSubstitute中有类似的东西吗?

sam*_*amy 5

无法更改您在 中收到的消息ReceivedCallException;它是直接从方法中的硬编码字符串构建的NSubstitute.Core.ReceivedCallsExceptionThrower Throw

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());
}
Run Code Online (Sandbox Code Playgroud)

除非您准备好深入研究 NSubstitute 代码,否则目前最好的选择是捕获ReceivedCallsException并抛出您自己的消息。