有没有办法在NSubstitute的类返回值上获取递归模拟

时间:2012-05-15 16:56:17

标签: c# mocking nsubstitute

NSubstitute在其docs中说明了这一点:

  

返回接口[...]的方法将自动返回替换。

这通常足够了。但是,当我这样做时:

TestMethod的:

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

实际方法:

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

        myObject = container.Resolve<ISomeObject>();

        myObject.CallSomeMethod();
    }

Resolve Method返回一个类。所以它没有被嘲笑。这意味着当我调用CallSomeMethod;

时,myObject中的null和null引用异常

如果我能够获得一个返回的类,那将是很好的(除非我特别重写了该接口)。

有没有办法使用 NSubstitute 来获得这个?

1 个答案:

答案 0 :(得分:2)

如果ISomeObject是一个接口,这应该可以正常工作。如果要获取自动替换类,则该类需要具有默认构造函数,并将其所有公共成员声明为虚拟成员。

以下测试通过我:

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