C# 有没有办法告诉Autofixture仅设置具有特定属性的属性?

C# 有没有办法告诉Autofixture仅设置具有特定属性的属性?,c#,unit-testing,dependency-injection,mocking,autofixture,C#,Unit Testing,Dependency Injection,Mocking,Autofixture,我使用Unity进行依赖项注入,在一些地方我使用属性注入(使用[dependency]属性)而不是构造函数注入 我想使用AutoFixture作为单元测试的模拟容器,但默认情况下,它会设置被测试系统上的所有公共属性。我知道我可以明确排除特定属性,但有没有办法只包括具有[Dependency]属性的属性 public class PropertyBuilder : ISpecimenBuilder { public object Create(object request, ISpecim

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

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

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);
}
公共类DependencyAttribute:属性
{
}
公共类TestClass
{
[依赖性]
带有{get;set;}的公共字符串
不带{get;set;}的公共字符串
}
[事实]
public void only带有DependencyAttributeAreResolved()的属性
{
//夹具设置
var夹具=新夹具
{
自定义设置={new PropertyBuilder()}
};
//运动系统
var sut=fixture.Create();
//核实结果
Assert.NotNull(sut.With);
Assert.Null(sut.Without);
}

为什么要使用属性注入?@MarkSeemann,因为在某些情况下更方便。典型的用例是当我有一个继承层次结构时;将依赖项传递给基类构造函数很难维护,因为如果我对基类有依赖项,我必须更改所有派生类构造函数。这不是使用属性注入的好理由。这是一种尝试(一定要阅读评论)。这不是一场无休止的辩论。AFAICT,现在大部分都结束了,构造函数注入赢了。在的第4章中,我详细描述了实现属性注入的所有问题。在大多数情况下,房地产注入是一个糟糕的选择,原因很清楚,也很容易解释。从那些有不同想法的人那里,我从来没有听到过任何其他关于他们“更喜欢财产注入”的论点,这几乎不是一个论点。@MarkSeemann是对的;这不是一场无休止的辩论。不要使用属性注入!这非常有效,我只是将它包装在一个iCustomize中,以便更流畅地使用。谢谢