为单元测试设置类的只读属性

时间:2016-12-22 10:19:07

标签: c# unit-testing readonly nsubstitute

我有这样的界面

public interface IConnection
{
    Strategy Gc { get; }

    bool IsConnected();

    bool Connect();
}

我想要使用此接口的类的单元测试方法。现在我想设置Gc,但它恰好是readonly。有没有办法设置Gc字段而不更改此接口类? 我正在使用MS fakes和Nsubstitute进行单元测试。然而,显然没有人提供解决方案。 PrivateObject也不起作用。

不能选择更改界面。建议更好的解决方案。

1 个答案:

答案 0 :(得分:9)

使用NSubstitute非常简单。首先为您的界面创建一个模拟器:

var mock = Substitute.For<IConnection>();

现在,您可以通过为属性设置任何返回类型来模拟成员:

mock.Gc.Returns(Substitute.For<Strategy>());

最后根据该实例将该模拟实例作为参数提供给服务,例如:

var target = new MyClassToTest();
target.DoSomething(mock);  // mock is an instance of IConnection

现在无论何时调用方法,它都会为Strategy返回一个dumm-instance。当然,您也可以在Returns语句中设置任何其他任意返回类型。如需了解更多信息,请查看http://nsubstitute.github.io/help/set-return-value