AutoFixture and AutoData with Spring.net

117 views Asked by At

In our projects we are using spring.net and nhibernate to persist our domain-entities. Out Test Data Builder partly persists entities, so they are also using spring.net.

I came across AutoFixture and AutoData and tried to use it for our tests, to reduce the arrange part of the unit tests by injecting entity instances via AutoData.

[Test, BuilderAutoData]
public void TestAutoFixture(City city1, City city2, User user, User user2) {
     // ... Assert something
}

I tried to customize auto data by implementing BuilderAutoDataAttribute and a BuilderAutoDataCustomization:

public class BuilderAutoDataAttribute : AutoDataAttribute {
    public BuilderAutoDataAttribute() : base(new Fixture().Customize(new BuilderAutoDataCustomization())) {
    }
}

public class BuilderAutoDataCustomization : ICustomization {
    public void Customize(IFixture fixture) {
        fixture.Register<User>(() => Create.A.User);
        fixture.Register<City>(() => Create.A.City);
        fixture.Register<District>(() => Create.A.District);
    }
}

Now I am facing the problem, that Create.A.User (calling the test data builder) is invoked before the spring-context is registered and an exception is thrown, because there is no spring-context.

public static class Create {
    public static class A {
        public static CityBuilder City {
            get {
                // instantiate Builder from spring
                return ContextRegistry.GetContext().GetObject<CityBuilder>();
            }
        }
        public static UserBuilder User {
            get {
                return ContextRegistry.GetContext().GetObject<UserBuilder>();
            }
        }
    }
}

Is there any chance of using AutoData with a factory using Spring.net (or something created in the Test-Setup)?

0

There are 0 answers