我正在为类(我们称之为 Sut
)编写测试,它有一些通过构造函数注入(inject)的依赖项。对于这个类,我必须使用参数最多的构造函数,因此我使用了 AutoMoqDataAttributeGreedy
实现:
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute() : base(new Fixture().Customize(new AutoMoqCustomization()))
{
}
}
public class AutoMoqDataAttributeGreedy : AutoDataAttribute
{
public AutoMoqDataAttributeGreedy() : base(new Fixture(new GreedyEngineParts()).Customize(new AutoMoqCustomization()))
{
}
}
我的 sut 的构造函数如下所示:
public class Sut(IInerface1 interface1, IInterface2 interface2, IInterface3 interface3)
{
Interface1 = interface1;
Interface2 = interface2;
Interface3 = interface3;
}
一个示例测试如下所示:
[Theory, AutoMoqDataAttributeGreedy]
public void SomeTest([Frozen]Mock<IInterface1> mock1 ,
Mock<IInterface2> mock2,
Sut sut,
SomOtherdata data)
{
// mock1 and mock2 Setup omitted
// I want to avoid following line
sut.AddSpeficicInterfaceImplementation(new IInterface3TestImplementation());
sut.MethodIWantToTest();
//Assert omitted
}
问题是我需要 IInterface3
的特定实现来进行测试,我想避免向我的 SUT (Interface3TestImplementation
) 添加仅用于我的单元测试的方法,并且我还想避免重复代码,因为我必须在每个测试中添加这个实例。
是否有一种巧妙的方法可以为我的所有测试/使用 Autofixture 的特定测试添加此实现?
最佳答案
如果您需要将此作为一次性测试来执行,那么 Enrico Campidoglio 的答案就是可行的方法。
如果您需要将此作为贯穿所有单元测试的一般规则,您可以使用 TypeRelay
自定义 Fixture
:
fixture.Customizations.Add(
new TypeRelay(
typeof(IInterface3),
typeof(IInterface3TestImplementation));
这将更改 fixture
,以便在需要 IInterface3
时,将创建并使用 IInterface3TestImplementation
的实例。
关于c# - 如何添加使用 Autofixture 创建的 Mock 的特定实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34788365/