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

时间:2015-04-28 09:44:03

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

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

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

1 个答案:

答案 0 :(得分:6)

这有效:

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);
}