Autowiring mock objects to spring beans using @Autowired

Today I needed to test some rest services implemented with Jaxrs and Jersey, My intention was to have a fast running unit test that can be run on CI build and will test that the jaxrs+spring wiring, json serialization etc. don't break. All my resources are just calling other internal services, so I decided to deploy my rest resources and wire mock objects to them on an embedded jetty server.

I used spring annotations to wire everything up and all my resources look like that:

 

@Component("myResource")
@Path("/somepath")
public class SomeResource {

    @Autowired
    private mocktest.SomeService someService;
...

 

so the easy way to mock SomeService would be to just create an Easymock factory-method bean:

 

<bean id="myServiceMock"  class="org.easymock.EasyMock" factory-method="createMock">
            <constructor-arg value="mocktest.SomeService" />
</bean>

 

But spring does not support the @Autowired annotation with factory-method. the easiest solution would be to use @Resource or @Autowired with @Qualifier.

But there's another thing, because I'm deploying this into an embedded jetty server and my unit tests will actually access the rest resources over http I don't have a hook to record the mock methods in the unit test class.

My solution is a spring FactoryBean for every service I want to mock, spring @Autowired works with FactoryBeans, and the getObject method of the factory bean is a great point to record mock methods, this is how a getObject looks like:

 

import static org.easymock.EasyMock.*;
public class SomeServiceMockFactoryBean implements FactoryBean<SomeService>{

    public SomeService getObject() throws Exception {
        SomeService mock = createMock(SomeService.class);
        //teach the mock to walk
        expect(mock.getSomeString()).andStubReturn("stub string");
        replay(mock);
        return mock;
    }
...

 

The returned mock is a mock ready for replay, and of course you can teach it many other things to do.

 And this is how the spring config for the FactoryBean looks like:

 

<bean id="myServiceMock" class="mocktest.SomeServiceMockFactoryBean"/>

 

 

Thanks.

 

 

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com