samedi 30 janvier 2016

Injecting Mocked objects using FactoryBean

I have a FactoryBean (Spring) defined as follows:

public class AMockFactoryBean extends EasyMockFactoryBean<A>{

    public AMockFactoryBean() {
        super(A.class);
    }

    @Override
    public A getObject() throws Exception {
        MockA a= new MockA();
        a.setB(createMock(B.class));
        return new MockA();
    }
}

The class A has an object of type B autowired:

public abstract class A {

    @Autowired
    protected B b;

}

MockA implements a few abstract classes and EasyMockFactoryBean utilizes the Spring FactoryBean method.

In my app.xml config I have:

<bean id="mockedA" class="AMockFactoryBean" />

My test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:testContext.xml")
public class ATest {

    @Autowired
    private A mockedA;

}

Result: mockedA in ATest is autowired correctly, but the autowired field A.b has been set to null by Spring. In debug mode I see how getObject() in AMockFactoryBean is called and how mockedA is given a Mock instance of EasyMock. But when the debugger jumps into the ATest class, mockedA.b is null. Why?

Aucun commentaire:

Enregistrer un commentaire