简体   繁体   English

AutoFixture AutoMoq 部分覆盖 class 构造函数

[英]AutoFixture AutoMoq partially covers class constructor

I am using AutoFixture AutoMoq and it's greatly simplifies the mock for all interface used in class and initialize it.我正在使用 AutoFixture AutoMoq,它极大地简化了 class 中使用的所有接口的模拟并对其进行初始化。

Though I noticed the constructor code is partially covered, can we modify AutoMoqDataAttribute so that constructor ArgumentNullException can also be covered?虽然我注意到构造函数代码被部分覆盖,但我们可以修改AutoMoqDataAttribute以便也可以覆盖构造函数ArgumentNullException吗?

在此处输入图像描述

public class ServiceTest
{
    [Theory, AutoMoqData]
    public async Task Do_Test_For_DoMethod(Service sut)
    {
        await sut.DoMethod();
    }
}

AutoMoqData attribute class, AutoMoqData 属性 class,

public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(() => new Fixture().Customize(new AutoMoqCustomization()))
    {

    }
}

Service class code,服务 class 代码,

 public class Service
{
    private readonly IServiceClient _serviceClient;
    private readonly ILogger<Service> _logger;

    public Service(IServiceClient serviceClient, ILogger<Service> logger)
    {
        _serviceClient = serviceClient ?? throw new ArgumentNullException(nameof(serviceClient));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }


    public async Task DoMethod()
    {

        await _serviceClient.Do();
    }
}

It is not the responsibility of the AutoDataAttribute to know how to cover your code. AutoDataAttribute不负责了解如何覆盖您的代码。 It is the developers responsibility to express intent and explicitly cover the scenario.表达意图并明确涵盖场景是开发人员的责任。

In your case the uncovered branches are the null guards.在您的情况下,未覆盖的分支是 null 警卫。 Luckily AutoFixture provides a library just for that, AutoFixture.Idioms .幸运的是 AutoFixture 专门为此提供了一个库AutoFixture.Idioms

This library provides idiomatic assertions, that encapsulate most basic test scenarios like null guards, property setters, equality members and so on.这个库提供惯用的断言,封装了最基本的测试场景,如null保护、属性设置器、相等成员等。

Using this library you can write a test like the following.使用这个库,您可以编写如下测试。

[Theory, AutoMockData]
void CheckGuards(GuardClauseAssertion assertion)
{
   assertion.Verify(typeof(Service));
}

This should cover all the parameters of all the constructors, and the nice part is that it uses your customization, so it will generate valid data when attempting to instantiate your object.这应该涵盖了所有构造函数的所有参数,而且好的部分是它使用了您的自定义,因此在尝试实例化您的 object 时它将生成有效数据。

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

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