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

问题描述 投票:0回答:2

有办法向 NSubstitute 查询接听电话数量是否在一定范围内吗?

我想做这样的事情:

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

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

c# mocking nsubstitute
2个回答
9
投票

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

有一种使用 unofficial

.ReceivedCalls
扩展的 hacky 方式:

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


0
投票

这是一篇旧文章,但

nsubstitute
现在确实支持开箱即用

// RangeQuantity is exposed via 'Within'
mockObject.Received(Quantity.Within(3,5)).YourMethod(...);
© www.soinside.com 2019 - 2024. All rights reserved.