Injecting Mockito mocks into a Spring bean

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

    I developed a solution based on the proposal of Kresimir Nesek. I added a new annotation @EnableMockedBean in order to make the code a bit cleaner and modular.

    @EnableMockedBean
    @SpringBootApplication
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes=MockedBeanTest.class)
    public class MockedBeanTest {
    
        @MockedBean
        private HelloWorldService helloWorldService;
    
        @Autowired
        private MiddleComponent middleComponent;
    
        @Test
        public void helloWorldIsCalledOnlyOnce() {
    
            middleComponent.getHelloMessage();
    
            // THEN HelloWorldService is called only once
            verify(helloWorldService, times(1)).getHelloMessage();
        }
    
    }
    

    I have written a post explaining it.

提交回复
热议问题