使用 NSubstitute 检查接听电话的数量是否在范围内

Check that number of received calls is within range with NSubstitute

有没有办法用 NSubstitute 检查接听电话的数量是否在一定范围内?

我想做这样的事情:

myMock.Received(r => r > 1 && r <= 5).MyMethod();

或者,如果我能获得已接电话的确切数量,也能完成这项工作。我正在单元测试重试和超时,并基于系统负载和其他测试 运行 在单元测试执行期间重试次数可能会有所不同。

NSubstitute API 目前不完全支持这一点(但这是个好主意!)。

有一种 hacky-ish 使用 unofficial .ReceivedCalls 扩展的方法:

var calls = myMock.ReceivedCalls()
    .Count(x => x.GetMethodInfo().Name == nameof(myMock.MyMethod));
Assert.InRange(calls, 1, 5);

更好的方法是使用来自 NSubstitute.ReceivedExtensions 命名空间的自定义 Quantity

// DISCLAIMER: draft code only. Review and test before using.
public class RangeQuantity : Quantity {
    private readonly int min;
    private readonly int maxInclusive;
    public RangeQuantity(int min, int maxInclusive) {
        // TODO: validate args, min < maxInclusive.
        this.min = min;
        this.maxInclusive = maxInclusive;
    }
    public override string Describe(string singularNoun, string pluralNoun) => 
        $"between {min} and {maxInclusive} (inclusive) {((maxInclusive == 1) ? singularNoun : pluralNoun)}";

    public override bool Matches<T>(IEnumerable<T> items) {
        var count = items.Count();
        return count >= min && count <= maxInclusive;
    }

    public override bool RequiresMoreThan<T>(IEnumerable<T> items) => items.Count() < min;
}

然后:

myMock.Received(new RangeQuantity(3,5)).MyMethod();

(请注意,您需要 using NSubstitute.ReceivedExtensions;。)