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
Update: There are now better, cleaner solutions to this problem. Please consider the other answers first.
I eventually found an answer to this by ronen on his blog. The problem I was having is due to the method Mockito.mock(Class c)
declaring a return type of Object
. Consequently Spring is unable to infer the bean type from the factory method return type.
Ronen's solution is to create a FactoryBean
implementation that returns mocks. The FactoryBean
interface allows Spring to query the type of objects created by the factory bean.
My mocked bean definition now looks like: