自动混合测试接口类型参数的保护条件

时间:2015-06-26 21:32:30

标签: 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" - 以及这种构造函数出现的频率,我不确定为什么我需要模拟构造函数参数时它是一种抽象类型,但不是它的具体类型。

1 个答案:

答案 0 :(得分:2)

默认情况下,AutoFixture仅会创建new向上的类型。无法创建抽象类型/接口。如果添加其中一个AutoFixture-Mocking程序集,则可以将AutoFixture转换为AutoMocking容器。因此,当它检测到您正在传递抽象类型/接口时,而不是混淆它将为您创建模拟。

AutoMocking版本包括: