Injecting Mockito mocks into a Spring bean
Posted
by teabot
on Stack Overflow
See other posts from Stack Overflow
or by teabot
Published on 2010-03-16T18:58:07Z
Indexed on
2010/03/17
10:21 UTC
Read the original article
Hit count: 822
I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired
annotation on private member fields.
I have considered using ReflectionTestUtils.setField
but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing.
I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails:
<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.Dao" />
</bean>
The error I currently encounter is as follows:
...
Caused by: org...NoSuchBeanDefinitionException:
No matching bean of type [com.package.Dao] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {
@org...Autowired(required=true),
@org...Qualifier(value=dao)
}
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)
If I set the constructor-arg
value to something invalid no error occurs when starting the application context.
© Stack Overflow or respective owner