Chry Cheng
Chry Cheng

Reputation: 3468

How to stub a method by matching an argument by a superclass in NSubstitute?

Referring to the following sample code:

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

The assert fails indicating that Method stub was not matched. Did I misunderstand the argument matcher documentation page which claims that Arg.Any can be used "to match any argument of a specific sub-type"?

Upvotes: 1

Views: 180

Answers (1)

Chry Cheng
Chry Cheng

Reputation: 3468

It appears that the problem isn't in argument matching but in the stubbing. Method must be virtual or it won't get stubbed:

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

Upvotes: 2

Related Questions