【问题标题】:How to stub a method by matching an argument by a superclass in NSubstitute?如何通过匹配 NSubstitute 中的超类的参数来存根方法?
【发布时间】:2018-06-18 01:26:11
【问题描述】:

参考以下示例代码:

using NSubstitute;
using NUnit.Framework;

public class Class1
{
}

public class Class2
{
    public void Method(Class1 class1)
    {
    }
}

public class Class3 : Class1
{
}

[TestFixture]
public class ArgAnyTest
{
    [Test]
    public void Test()
    {
        var called = false;
        var class2 = Substitute.For<Class2>();
        class2.When(@this => @this.Method(Arg.Any<Class1>())).Do(invocation => called = true);

        class2.Method(new Class3());

        Assert.That(called, Is.EqualTo(true));
    }
}

断言失败,表明Method 存根不匹配。我是否误解了 argument matcher 文档页面,该页面声称 Arg.Any 可用于“匹配特定子类型的任何参数”?

【问题讨论】:

    标签: c# unit-testing nsubstitute stubbing argument-matching


    【解决方案1】:

    看来问题不在于参数匹配,而在于存根。 Method 必须是虚拟的,否则不会被存根:

    public class Class2
    {
        virtual public void Method(Class1 class1)
        {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2017-01-14
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多