c# - Autofixture 测试接口(interface)类型参数的保护条件

标签 c# autofixture

我正在尝试使用 AutoFixtureAutofixture.Idioms 来简化构造函数中保护条件的测试。我正在使用以下熟悉的、几乎样板的方法进行测试:

[TestMethod]
public void DependencyConsumerContainsAGuardCondition ( )
{
    var fixture = new Fixture ( );
    var assertion = new GuardClauseAssertion ( fixture );
    assertion.Verify ( typeof ( DependencyConsumer ).GetConstructors ( ) );
}

DependencyConsumer 的构造函数是具体类型时,运行测试没有问题:

public interface IDependency { } 

public class ConcreteDependency : IDependency { } 

public class DependencyConsumer
{
    public DependencyConsumer(ConcreteDependency dependency)
    {
        if (dependency == null)
        {
            throw new ArgumentNullException ( "dependency" );
        }
    }
}

但是,当我将构造函数参数的类型更改为 IDependency 时,测试失败并出现以下异常(为了可读性而重新格式化)

Test method
    AutomatedTestingPlayground.Playground.DependencyConsumerContainsAGuardCondition
    threw exception: 
Ploeh.AutoFixture.Idioms.GuardClauseException: AutoFixture was unable to
    create an instance for parameter "dependency" of method ".ctor".
Method Signature: Void .ctor(AutomatedTestingPlayground.IDependency)
Declaring Type: AutomatedTestingPlayground.DependencyConsumer
Reflected Type: AutomatedTestingPlayground.DependencyConsumer --->
    Ploeh.AutoFixture.ObjectCreationException: AutoFixture was unable to
    create an instance from AutomatedTestingPlayground.IDependency, most
    likely because it has no public constructor, is an abstract or
    non-public type.

Request path:
      AutomatedTestingPlayground.IDependency

我的测试设置代码中缺少什么?我是否需要显式模拟 IDependency 并将其作为构造函数参数提供?考虑到 AutoFixture 的既定目标——“零摩擦 TDD”——以及此类构造函数出现的频率,我不确定为什么我需要在构造函数参数是抽象类型时模拟它,而不是在它是抽象类型时模拟构造函数参数。具体类型。

最佳答案

默认情况下,AutoFixture 只会创建您可以新建的类型。无法创建抽象类型/接口(interface)。如果您添加各种 AutoFixture-Mocking 组件之一,它们可以将 AutoFixture 变成 AutoMocking 容器。因此,当它检测到您正在传递抽象类型/接口(interface)时,它不会感到困惑,而是会为您创建 Mock。

AutoMocking 版本包括:

关于c# - Autofixture 测试接口(interface)类型参数的保护条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082476/

相关文章:

c# - Selenium WebDriver 测试登录验证

c# - 您可以将内联值与 AutoFixture 中的 AutoData 结合起来吗?

c# - 如何最大程度地减少或通知用户数据库连接延迟/失败?

c# - 事件采购资源

c# - 使用 AutoFixture 和 Moq 模拟 HttpResponse.StatusCode

c# - 如何简化单元测试 DDD Value objects Equality with AutoFixture

unit-testing - 如何使用 AutoFixture 创建对象但不填写任何属性

c# - 如何将数据从 ASP.Net 插入到 MS SQL Server?

c# - 如果在 LINQ 中找到,如何在最后一条记录上应用包含并删除?