我正在尝试使用 AutoFixture
和 Autofixture.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/