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

Is there a way to tell Autofixture to only set properties with a specific attribute?

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

我想将 AutoFixture 用作我的单元测试的模拟容器,但默认情况下它会在被测系统上设置所有 public 属性。我知道我可以明确排除特定属性,但有没有办法只包含具有 [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);
}