使用NSubstitute

时间:2019-05-06 22:15:16

标签: c# mocking nsubstitute

是否可以通过NSubstitute检查已接电话数量是否在一定范围内?

我想做类似的事情:

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

或者,如果我可以得到准确的接听电话数量,那么同样可以完成这项工作。我是单元测试重试和超时,并且基于系统负载和其他测试,运行重试的次数在单元测试执行期间可能会有所不同。

1 个答案:

答案 0 :(得分:1)

NSubstitute API当前不完全支持此功能(但这是一个好主意!)。

使用unofficial .ReceivedCalls扩展名可以做到这一点:

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

使用Quantity命名空间中的自定义NSubstitute.ReceivedExtensions来实现此目的的更好方法:

// 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;。)