I use mockito as a mock object library. I am unit testing DAOs.
DAOs expect JdbcTemplate to be injected through @Autowired. Hence, there are no setter methods for JDBC Template in DAOs which unit tests can call.
I have the following test spring application context:
<b:beans
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:annotation-config />
<b:bean id="mockito" class="org.mockito.Mockito" />
<b:bean
id="mockJdbcTemplate"
factory-bean="mockito"
factory-method="mock">
<b:constructor-arg value="org.springframework.jdbc.core.JdbcTemplate"/>
</b:bean>
</b:beans>
I was expecting that at test execution time, spring will create mock jdbctemplate instance and autowire it to DAO.
But that doesn’t happen – instead I just get the following exception:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 42 more
Has anyone had success with this approach before?
Thanks.
I think the problem is that the factory method
mockwhich returns generic type. After erasure, the spring is not able to deduct object type, try to provide explicit object type byclassattribute.