简体   繁体   English

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

[英]Setting a readonly property of a class for unit testing

I have an interface like this 我有这样的界面

public interface IConnection
{
    Strategy Gc { get; }

    bool IsConnected();

    bool Connect();
}

I want to unit test methods of a class that uses this interface. 我想要使​​用这个接口的类的单元测试方法。 Now I want to set Gc but it happens to be readonly. 现在我想设置Gc,但它恰好是readonly。 Is there a way to set Gc field without making changes to this interface class? 有没有办法设置Gc字段而不更改此接口类? I am using MS fakes and Nsubstitute for unit testing. 我正在使用MS fakes和Nsubstitute进行单元测试。 However, apparently none provides a solution. 然而,显然没有人提供解决方案。 PrivateObject does not work either. PrivateObject也不起作用。

Changing Interface is not an option. 更改界面不是一个选项。 Suggest better solutions. 建议更好的解决方案。

With NSubstitute it is quite easy. 有了NSubstitute这很容易。 First create a mock for your interface: 首先为您的界面创建一个模拟:

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

Now you can mock the member by setting any return-type for the property: 现在,您可以通过为属性设置任何返回类型来模拟成员:

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

Finally provide that mocked instance as parameter to the service depending on that instance, for example: 最后根据该实例将该模拟实例作为参数提供给服务,例如:

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

Now whenever your method is called it returns a dumm-instance for Strategy . 现在无论何时调用您的方法,它都会为Strategy返回一个dumm-instance。 Of course you can also set any other arbitrary return-type within the Returns -statement. 当然,您还可以在Returns -statement中设置任何其他任意返回类型。 Just have a look at http://nsubstitute.github.io/help/set-return-value for further information. 只需查看http://nsubstitute.github.io/help/set-return-value以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM