简体   繁体   中英

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 Ab 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?

You return return new MockA(); instead of a. Your code should be @Override public A getObject() throws Exception { MockA a= new MockA(); a.setB(createMock(B.class)); return a; } @Override public A getObject() throws Exception { MockA a= new MockA(); a.setB(createMock(B.class)); return a; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM