Is there a way to get recursive mocks on a class return value with NSubstitute

StackOverflow https://stackoverflow.com/questions/10605450

  •  09-06-2021
  •  | 
  •  

سؤال

NSubstitute says this in its docs:

methods that return an interface [...] will automatically return substitutes themselves.

That is enough usually. However, when I do this:

TestMethod:

IUnityContainer unity = Substitute.For<IUnityContainer>();
MyMethod(unity);

Actual Method:

    public void MyMethod(IUnityContainer container)
    {
        this.container = container;

        myObject = container.Resolve<ISomeObject>();

        myObject.CallSomeMethod();
    }

The Resolve Method returns a class. So it is not mocked. That means I get null in myObject and a null reference exception when I call CallSomeMethod;

It would be nice if I could just get a class returned that is a mock (that is unless I have overridden that interface specifically).

Is there any way to get this using NSubstitute?

هل كانت مفيدة؟

المحلول

If ISomeObject is an interface this should work fine. If you want to get auto-substitute classes, the class needs to have a default constructor, and have all it's public members declared as virtual.

The following tests pass for me:

public interface IFactory { T Resolve<T>(); }
public interface ISomeObject { void CallSomeMethod(); }

public class Tests
{
    [Test]
    public void Example()
    {
        var factory = Substitute.For<IFactory>();
        MyMethod(factory);
    }
    public void MyMethod(IFactory container)
    {
        var myObject = container.Resolve<ISomeObject>();
        myObject.CallSomeMethod();
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top