【问题标题】:Setting a readonly property of a class for unit testing为单元测试设置类的只读属性
【发布时间】:2016-12-22 10:19:07
【问题描述】:

我有这样的界面

public interface IConnection
{
    Strategy Gc { get; }

    bool IsConnected();

    bool Connect();
}

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

更改界面不是一种选择。提出更好的解决方案。

【问题讨论】:

    标签: c# unit-testing readonly nsubstitute


    【解决方案1】:

    使用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 返回一个哑实例。当然,您也可以在Returns-statement 中设置任何其他任意返回类型。请查看http://nsubstitute.github.io/help/set-return-value 了解更多信息。

    【讨论】:

    • 成功了,谢谢。我摸不着头脑我怎么没有尝试过。
    猜你喜欢
    • 2022-01-23
    • 2014-08-16
    • 2016-02-25
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多