unit-testing - NSubstitute:无法模拟与没有相应 setter 的成员变量关联的语法糖 getter 方法

标签 unit-testing mocking nsubstitute stubbing

对于我的 .NET C# 应用程序,我正在使用名为 efaxdeveloper.com 的第三方电子传真软件

我需要模拟 efaxdeveloper.com 的软件 OutboundResponse 对象。

请记住,由于它是第 3 方,我显然不能修改第 3 方 dll。

在 eFaxDeveloper.dll 中,OutboundResponse 类的代码如下:

using System.Runtime.InteropServices;

namespace J2.eFaxDeveloper.Outbound
{
    //
    // Summary:
    //     oubound response
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [System.Runtime.Serialization.DataContractAttribute(Namespace = "")]
    public class OutboundResponse
    {
        public OutboundResponse();

        //
        // Summary:
        //     Unique client specified transmission identifier
        public string TransmissionID { get; }
        //
        // Summary:
        //     eFax Developer™ transmission identifier
        public string DOCID { get; }
        //
        // Summary:
        //     J2.eFaxDeveloper.Outbound.StatusCode
        public StatusCode StatusCode { get; }
        //
        // Summary:
        //     Status description
        public string StatusDescription { get; }
        //
        // Summary:
        //     J2.eFaxDeveloper.Outbound.ErrorLevel
        public ErrorLevel ErrorLevel { get; }
        //
        // Summary:
        //     Error message
        public string ErrorMessage { get; }
    }
}

由于它只有 setter/getter ,我尝试了以下代码片段:
    OutboundResponse outboundResponseInQuestion = Substitute.For<OutboundResponse>();

    outboundResponseInQuestion.TransmissionID.Returns("someTransmissionID");

不幸的是, outboundResponseInQuestion.TransmissionID 抛出

“outboundResponseInQuestion.TransmissionID”引发了“System.NullReferenceException”类型的异常

我无法为 OutboundResponse 类创建接口(interface),所以有人可以告诉我如何使用 NSubstitute 模拟所述对象并使其返回正确的值吗?

最佳答案

NSubstitute 无法模拟此类型,因为它没有 virtual成员。 (出于同样的原因,我们也不能手动创建 OutboundResponse 的子类型,它会覆盖 getter 并公开 setter 并将其用于测试。)

通过创建一个封装了来自 3rd 方库 (facade pattern) 的全部所需行为的接口(interface)并测试您的代码与该接口(interface)的交互,您可能会更轻松。然后,您可以在调用 3rd 方库时单独测试该接口(interface)的实现是否会产生正确的结果。这些可能是集成或手动测试。
<shamelessplug>我之前写过一些关于 downsides of mocking types we don't own 的文章。你可能会觉得有用。 </shamelessplug>

关于unit-testing - NSubstitute:无法模拟与没有相应 setter 的成员变量关联的语法糖 getter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55054764/

相关文章:

unit-testing - Dart Angular 在单元测试中用模拟替换提供者

.net - 如何在 NSubstitute 中使用私有(private) setter 模拟对象的索引器?

c# - 如何模拟 NSubstitute 中返回对象的索引器信息

ios - 旧版 ObjC/Swift 代码库使 `swift_checkMetadataState` : how to disentangle app/test targets? 中的测试崩溃

c# - 最小起订量和构造函数 - 测试初始化​​行为

java - 如何在 Google Appengine 代码上使用 Google CodePro Coverage?

unit-testing - VS2010(专业版)的所有免费集成代码覆盖工具

unit-testing - 在 AngularJS 2 中使用 AuthHttp 模拟 http 调用

c# - 设置字符串参数时,模拟上的所有调用都必须有相应的设置

linq - NSubstitute 不匹配 Linq 表达式