c# - 通过 AutoFixture 使用私有(private) setter 测试数据填充公共(public)属性

标签 c# unit-testing autofixture

我想测试 ConfirmDownloadInvoiceDate 方法。此外,我想通过以下方式使用 ConfirmationDownloadInvoiceDate 属性的测试数据创建 Order 对象:

fixture.Create<Order>();

我的订单类:

public class Order
{       
    public DateTime? ConfirmationDownloadInvoiceDate { get; private set; }

    public void ConfirmDownloadInvoiceDate(IDateTimeProvider timeProvider)
    {
        if (ConfirmationDownloadInvoiceDate == null)
        {
            ConfirmationDownloadInvoiceDate = timeProvider.Now();
        }
    }
}

是否可以用测试数据填充该属性?我尝试从 ISpecimenBuilder 创建新类,但它似乎不起作用。

最佳答案

根据设计,AutoFixture 仅在字段和属性可公开写入时才填充它们,因为如果您不使用 AutoFixture,而是手动编写测试数据排列阶段,那么作为客户端开发人员您可以自己做这些。在上面的 Order 类中,ConfirmationDownloadInvoiceDate 属性没有公共(public) setter ,因此 AutoFixture 将忽略它。

显然,最简单的解决方法是公开 setter ,但这并不总是必要的。

在这种特殊情况下,您可以通过告诉 AutoFixture 在创建 Order 时调用 ConfirmDownloadInvoiceDate 方法来自定义 Order 类的创建> 对象。

一种方法是首先创建一个 IDateTimeProvider 的特定于测试的 Stub 实现,例如:

public class StubDateTimeProvider : IDateTimeProvider
{
    public StubDateTimeProvider(DateTime value)
    {
        this.Value = value;
    }

    public DateTime Value { get; }

    public DateTime Now()
    {
        return this.Value;
    }
}

您还可以使用动态模拟库,例如 Moq、NSubstitute 等。

使用 stub 调用ConfirmDownloadInvoiceDate 方法,例如:

[Fact]
public void AutoFillConfirmationDownloadInvoiceDate()
{
    var fixture = new Fixture();
    fixture.Customize<Order>(c => c
        .Do(o => o.ConfirmDownloadInvoiceDate(fixture.Create<StubDateTimeProvider>())));

    var actual = fixture.Create<Order>();

    Assert.NotNull(actual.ConfirmationDownloadInvoiceDate);
    Assert.NotEqual(default(DateTime), actual.ConfirmationDownloadInvoiceDate);
}

这个测试通过了。您应该考虑将上述自定义打包到 ICustomization 类中。

关于c# - 通过 AutoFixture 使用私有(private) setter 测试数据填充公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049762/

相关文章:

c# - 找到与名为 'Account' 的 Controller 匹配的多个类型。 MVC 4 & 使用 RouteConfig.CS

c# - Rijndael加密/解密

c# - Resharper 中的警告 "Return value of pure method is not used"

c# - WCF 服务主机、服务端点和绑定(bind)

java - 测试生成的 HTML 代码的规范方法是什么?

unit-testing - 如何使用 Karma 和 PhantomJS 正确地对 ReactDOM.render 进行单元测试?

javascript - 我们可以使用 Jasmine 在测试中执行异步操作吗?

c# - 在使用 nSubstitute 和 Autofixture 作为 DI 容器的单元测试中,如何获取模拟对象?

c# - 带有 Entity Framework 的 AutoFixture - 将 int 映射到枚举

c# - 如果 IRepository 调用没有返回值,则使用 Moq 解决测试依赖关系的目的