Injecting Mockito mocks into a Spring bean

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

    Given:

    @Service
    public class MyService {
        @Autowired
        private MyDAO myDAO;
    
        // etc
    }
    

    You can have the class that is being tested loaded via autowiring, mock the dependency with Mockito, and then use Spring's ReflectionTestUtils to inject the mock into the class being tested.

    @ContextConfiguration(classes = { MvcConfiguration.class })
    @RunWith(SpringJUnit4ClassRunner.class)
    public class MyServiceTest {
        @Autowired
        private MyService myService;
    
        private MyDAO myDAOMock;
    
        @Before
        public void before() {
            myDAOMock = Mockito.mock(MyDAO.class);
            ReflectionTestUtils.setField(myService, "myDAO", myDAOMock);
        }
    
        // etc
    }
    

    Please note that before Spring 4.3.1, this method won't work with services behind a proxy (annotated with @Transactional, or Cacheable, for example). This has been fixed by SPR-14050.

    For earlier versions, a solution is to unwrap the proxy, as described there: Transactional annotation avoids services being mocked (which is what ReflectionTestUtils.setField does by default now)

提交回复
热议问题