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

I am using Unity for dependency injection and in several places I am using property injection (with attribute [Dependency]

) rather than constructor installation.

I would like to use AutoFixture as a mocking container for my unit tests, but by default it sets all public properties on the system under test. I know I can explicitly exclude specific properties, but is there a way to only include properties that have an attribute [Dependency]

?

+3


source to share


1 answer


It works:

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

      



Test case:

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

      

+6


source







All Articles