【问题标题】:Check that number of received calls is within range with NSubstitute使用 NSubstitute 检查接听电话的数量是否在范围内
【发布时间】:2019-05-06 22:15:16
【问题描述】:

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

我想做这样的事情:

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

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

【问题讨论】:

标签: c# mocking nsubstitute


【解决方案1】:

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

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

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

【讨论】:

  • 对于 NUnit 3,我不得不做 Assert.That(calls, Is.InRange(1 ,5)) 因为我找不到 Assert.InRange。
  • Assert.InRange 来自 XUnit。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2023-04-03
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多