微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当参数与给定模式不匹配时,如何让 NSubstitute 模拟失败?

如何解决当参数与给定模式不匹配时,如何让 NSubstitute 模拟失败?

我负责测试我的团队正在维护的用 C 和 C# 开发的遗留软件。原始团队使用 NSubstitute 3.1 为委托创建测试替身,以便对 C# 部分的 API 执行单元测试。这是一个这样的测试替身,其中忽略了不相关的细节:

private static byte[] MockSelectByAidWithoutData(ushort retVal)
{
    var expectedIn= "FFFEFDFCFB".HexToBytes();
    var expectedOut= "010203040506070809".HexToBytes();

    var fake = Substitute.For<SomeDelegate>();
    fake(Arg.Is<byte[]>(x => expectedIn.SequenceEqual(x.Take(expectedIn.Length))),Arg.Is(0x00),Arg.Is(expectedIn.Length),Arg.Any<int>(),out int outputLength)
        .Returns(x =>
            {
                expectedOut.copyTo((Array)x[0],0);
                x[5] = expectedOut.Length;
                return retVal;
            }
        );
    Mediator.GetInstance().Delegate = fake;
    return expectedOut;
}

现在,如果使用与 fake() 调用中指定的参数匹配的参数调用假委托,它会返回 retVal 值,并且每个人都很高兴。但是,如果某个值不匹配,则返回零。由于零是一个有效但不正确的值,执行继续,我得到一个错误,这不是我正在测试的问题的根本原因(即当问题实际上是错误的输入时输出错误

我正在寻找一种方法

  • 为不符合预期的值指定“一劳永逸”的行为,或
  • 如果参数与期望不匹配,则获得异常

这样测试用例会在接收到带有有意义消息的错误输入时立即失败,并且不会触发只会污染测试结果的进一步行为。

提前致谢,

DeK

附言如果真的有必要,我可能可以安全地切换到更新版本的 NSubstitute。

解决方法

为不符合预期的值指定“一网打尽”行为

我想我已经找到了一种方法可以做到这一点。如果您首先存根所有参数的“全部捕获”/失败情况,则可以存根更具体的调用。 NSubstitute 将尝试匹配提供的最新规范,回退到较早的存根值。

这是一个示例。

请注意,它使用的是 NSubstitute 4.x 中引入的 NSubstitute.Extensions 命名空间中的 Configure。这不是绝对必要的,因为如果您使用参数匹配器,NSubstitute 会自动假设您正在配置调用,但在配置像这样的重叠调用时,这是一个很好的模式。

using NSubstitute;
using NSubstitute.Extensions; // required for Configure()

public class Thing {
    public string Id { get; set; }
}

public interface ISample {
    int Example(Thing a,string b);
}

public class UnexpectedCallException : Exception { }

[Fact]
public void ExampleOfStubOneCallButFailOthers() {
    var sub = Substitute.For<ISample>();

    // Catch all case:
    sub.Example(null,null).ReturnsForAnyArgs(x => throw new UnexpectedCallException());

    // Specific case. We use Configure from NSubstitute.Extensions to
    // be able to stub this without getting an UnexpectedCallException.
    // Not strictly necessary here as we're using argument matchers so NSub
    // already knows we're configuring a call,but it's a good habit to get into.
    // See: https://nsubstitute.github.io/help/configure/
    sub.Configure()
        .Example(Arg.Is<Thing>(x => x.Id == "abc"),Arg.Any<string>())
        .Returns(x => 42);

    // Example of non-matching call:
    Assert.Throws<UnexpectedCallException>(() =>
        sub.Example(new Thing { Id = "def" },"hi")
    );

    // Example of matching call:
    Assert.Equal(42,sub.Example(new Thing { Id = "abc" },"hello"));
}

您可以扩展它以包含有关不匹配的参数的信息,但这将是一些自定义工作。如果您查看 NSubstitute 的一些参数格式化代码,这些代码可能可重复使用以帮助解决此问题。


更新以包含委托示例

我只是用一个委托来运行它,它也通过了:

public delegate int SomeDelegate(Thing a,string b);

[Fact]
public void ExampleOfStubOneDelegateCallButFailOthers() {
    var sub = Substitute.For<SomeDelegate>();
    sub(null,null).ReturnsForAnyArgs(x => throw new UnexpectedCallException());
    sub.Configure()
        .Invoke(Arg.Is<Thing>(x => x.Id == "abc"),Arg.Any<string>())
        .Returns(x => 42);
    Assert.Throws<UnexpectedCallException>(() => sub(new Thing { Id = "def" },"hi"));
    Assert.Equal(42,sub(new Thing { Id = "abc" },"hello"));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。