Injecting Mockito mocks into a Spring bean

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

    Posting a few examples based on the above approaches

    With Spring:

    @ContextConfiguration(locations = { "classpath:context.xml" })
    @RunWith(SpringJUnit4ClassRunner.class)
    public class TestServiceTest {
        @InjectMocks
        private TestService testService;
        @Mock
        private TestService2 testService2;
    }
    

    Without Spring:

    @RunWith(MockitoJUnitRunner.class)
    public class TestServiceTest {
        @InjectMocks
        private TestService testService = new TestServiceImpl();
        @Mock
        private TestService2 testService2;
    }
    

提交回复
热议问题