【问题标题】:Is there a way to tell Autofixture to only set properties with a specific attribute?有没有办法告诉 Autofixture 只设置具有特定属性的属性?
【发布时间】:2015-04-28 09:44:03
【问题描述】:

我使用 Unity 进行依赖注入,在一些地方我使用属性注入(带有[Dependency] 属性)而不是构造函数注入。

我想使用 AutoFixture 作为我的单元测试的模拟容器,但默认情况下它会在被测系统上设置所有公共属性。我知道我可以明确排除特定属性,但有没有办法只包含具有 [Dependency] 属性的属性?

【问题讨论】:

  • 你为什么要使用属性注入?
  • @MarkSeemann,因为在某些情况下它更方便。典型的用例是当我有一个继承层次结构时;将依赖项传递给基类构造函数很难维护,因为如果我对基类有依赖项,则必须更改所有派生类构造函数。
  • 这不是一场无休止的辩论。 AFAICT,现在基本结束了,构造函数注入赢了。在my book on the subject的第4章中,我详细描述了实现属性注入的所有问题。在大多数情况下,Property Injection 是一个糟糕的选择,原因很明确,易于解释。从那些想法不同的人那里,我从未听说过他们“更喜欢属性注入”的任何其他论点,这几乎不是论点。
  • @MarkSeemann 是对的;这不是无休止的辩论。不要使用属性注入!

标签: c# unit-testing dependency-injection mocking autofixture


【解决方案1】:

这行得通:

public class PropertyBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;
        if (pi != null)
        {
            if (pi.IsDefined(typeof (DependencyAttribute)))
                return context.Resolve(pi.PropertyType);

            //"hey, don't set this property"
            return new OmitSpecimen();
        }

        //"i don't know how to handle this request - go ask some other ISpecimenBuilder"
        return new NoSpecimen(request);
    }
}

fixture.Customizations.Add(new PropertyBuilder());

测试用例:

public class DependencyAttribute : Attribute
{
}

public class TestClass
{
    [Dependency]
    public string With { get; set; }

    public string Without { get; set; }
}

[Fact]
public void OnlyPropertiesWithDependencyAttributeAreResolved()
{
    // Fixture setup
    var fixture = new Fixture
    {
        Customizations = {new PropertyBuilder()}
    };
    // Exercise system
    var sut = fixture.Create<TestClass>();
    // Verify outcome
    Assert.NotNull(sut.With);
    Assert.Null(sut.Without);
}

【讨论】:

  • 这很好用,我只是将它包装在 ICustomization 中以便更流畅地使用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 2011-06-02
  • 2022-08-23
  • 1970-01-01
相关资源
最近更新 更多