Skip to content

Introduce FactoryBean to create mock beans with EasyMock [SPR-9130] #13769

Closed
@spring-projects-issues

Description

@spring-projects-issues

Dmitry Katsubo opened SPR-9130 and commented

Problem Area

I would like to have a myService definition in both production and test application contexts so that the service is further autowired into other services. The test application context should create a mock version of the bean, e.g. by means of IMocksControl.createMock().

Current Approach

The test application context defines:

<!-- Common for all mocks: -->
<bean name="mockCtrl" class="org.easymock.EasyMock" factory-method="createStrictControl" />

<bean name="myService" factory-bean="mockCtrl" factory-method="createMock">
	<constructor-arg value="org.company.api.MyService" />
</bean>
<!-- ...  other mock definitions ... -->

The drawback of this approach is that the given service can no longer be autowired with @Autowired MyService myService, but it can be injected with @Resource.

Analysis

The reason that the mock cannot be autowired by type is that the parametrized return type of the method configured via factory-method is not currently honored by Spring in all cases (i.e., depending on the order in which beans are defined in the context). In other words, the returned bean is not a candidate for autowiring by type for the type T (i.e., org.company.api.MyService in this example).

For a succinct discussion of this behavior, see the Explanation and Alternative solution sections of the Spring Integration Tests, Part I, Creating Mock Objects blog post.

Note that this is a general limitation of using factory-method in Spring; this is not specific to testing or mocks.

Furthermore, the same naturally applies to other mocking frameworks such as Mockito.

Proposal

The solution is to use a specific FactoryBean:

<bean name="myService" class="org.springframework.test.context.support.EasyMockFactoryBean"
	p:mockInterface="org.company.api.MyService" />

Related Resources


Affects: 3.1 GA

Attachments:

Issue Links:

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions