Injecting Mockito mocks into a Spring bean

后端 未结 22 1186
庸人自扰
庸人自扰 2020-11-22 09:44

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

22条回答
  •  情歌与酒
    2020-11-22 10:12

    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:

    
        
    
    

提交回复
热议问题