c# - 如何添加使用 Autofixture 创建的 Mock 的特定实现?

标签 c# tdd xunit autofixture

我正在为类(我们称之为 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/

相关文章:

c# - 在 SQL Server 中处理 'Enumerations' 有哪些不同的方法?

tdd - RhinoMock : Mocks Vs StrictMocks Vs DynamicMocks

refactoring - 哪些敏捷实践与游戏开发兼容?

c# - TFS 单元测试在开发机器上通过但在构建机器上失败

c# - 使用 XUnit 断言异常

c# - 在 xUnit 中加载程序集运行代码

xunit - 如何使用XUnit控制台输出NUnit格式的xml?

c# - 我的 XML 代码或 .NET 中是否存在错误?

c# - 来自 C# 代码隐藏的动态 Plotly 图

c# - 在 WCF 中将 ContractNamespace 用于命名空间枚举