How to wire your FitNesse fixtures with Spring

03 Nov, 2007
Xebia Background Header Wave

For testing my applications I like to use FitNesse and for writing my applications I tend to use Spring a lot. Since there is no way in FitNesse to override the mechanism how the Fixtures are instantiated you need to somehow load the Spring context and get the beans you want to test from the Spring context. You can of course do this by hand and retrieve the beans from the application context, but this kind of clutters your fixture code. Better is to let Spring take care of the wiring.

In order to let Spring wire your fixtures we can use the functionality offered by the AutowireCapableBeanFactory. If we create a ClassPathXmlApplicationContext we can obtain a reference to the AutowireCapableBeanFactory. The mechanism I describe here is actually also used in the AbstractDependencyInjectionSpringContextTests provided by Spring to inject you JUnit tests with Spring beans.
Here is the final code needed for injecting your fixtures:
Code to load spring context and wire fixtures:

public class FixtureWirer {
    private static AutowireCapableBeanFactory beanFactory;
    static {
        beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml").getAutowireCapableBeanFactory();
    public static void wire(Fixture fixture) {
        // make sure you AUTOWIRE_BY_NAME otherwise Spring will complain
        // about injecting the systemUnderTest property in the superclass which is of type object.
        beanFactory.autowireBeanProperties(fixture, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

Code in a fixture: (in this case a SetupFixture).

public class ApplicationSetup extends SetUpFixture {
    private SomeRepository someRepository;
    protected void setUp() throws Exception {
    public void setSomeRepository(SomeRepository someRepository) {
        this.someRepository = someRepository;
    // rest of fixture code where you can use someRepository omitted...

Happy testing.


Get in touch with us to learn more about the subject and related solutions

Explore related posts