为单元测试设置一个 class 的只读 属性

Setting a readonly property of a class for unit testing

我有这样的界面

public interface IConnection
{
    Strategy Gc { get; }

    bool IsConnected();

    bool Connect();
}

我想对使用此接口的 class 的方法进行单元测试。现在我想设置 Gc 但它恰好是只读的。有没有办法在不更改此接口的情况下设置Gc字段class? 我正在使用 MS fakes 和 Nsubstitute 进行单元测试。但是,显然 none 提供了解决方案。 PrivateObject 也不行。

更改界面不是一个选项。建议更好的解决方案。

有了NSubstitute就很容易了。首先为您的界面创建一个模拟:

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

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

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

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

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

现在,无论何时调用您的方法,它 return 都是 Strategy 的虚拟实例。当然,您也可以在 Returns-语句中设置任何其他任意 return-类型。请查看 http://nsubstitute.github.io/help/set-return-value 了解更多信息。