Injecting Mockito mocks into a Spring bean

后端 未结 22 1619
庸人自扰
庸人自扰 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

    I have a very simple solution using Spring Java Config and Mockito:

    @Configuration
    public class TestConfig {
    
        @Mock BeanA beanA;
        @Mock BeanB beanB;
    
        public TestConfig() {
            MockitoAnnotations.initMocks(this); //This is a key
        }
    
        //You basically generate getters and add @Bean annotation everywhere
        @Bean
        public BeanA getBeanA() {
            return beanA;
        }
    
        @Bean
        public BeanB getBeanB() {
            return beanB;
        }
    }
    

提交回复
热议问题