sara
sara

Reputation: 3609

NSubstitute - faking a virtual method that calls another virtual method

I have a class that looks something like this:

public class MyClass
{
    public virtual bool A()
    {
        return 5 < B();
    }

    protected virtual int B()
    {
        return new Random.Next(1, 10);
    }
}

When writing tests for MyClass it would be handy to be able to do the following:

[Fact]
public void Blabla()
{
    var o = Substitute.ForPartsOf<MyClass>();
    o.A().Returns(true);

    Assert.True(o.DoSomethingElse());
}

However, this doesn't work. I get a runtime exception:

NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException

Can not return value of type Boolean for MyClass.A (expected type int).

Is there a way to get around this, or do I have to create a concrete test double class overriding A?

Upvotes: 3

Views: 2986

Answers (1)

sara
sara

Reputation: 3609

I solved it by modifying the test-code as follows:

var o = Substitute.ForPartsOf<MyClass>();
o.When(x => x.A()).DoNotCallBase();
o.A().Returns(true);

Assert.True(o.DoSomethingElse());

This prevents the fake from calling the actual implementation in the following Returns() call.

Upvotes: 6

Related Questions