简体   繁体   中英

Use of Mocking with Spring

I am using junit with Spring and also mockito.While we are using Spring ,we have to load the spring config file.But by doing so we are getting all the real objects.What role dos mockito play in such scenarios?

If I am using this @ContextConfiguration(locations = {"classpath:/application-context.xml"}) in a test case that uses mockito ,i will be getting the objects from applicationContext.xml and those will be real objects.

how can mockito be utilized here

You don't have to use Spring to unit test your code. You can use Mockito @InjectMocks to inject dependencies into your class under test.

If you would like to unit test with Spring, yoou can use @ContextConfiguration annotation from Spring and define configuration in the test itself using mocks where appropriate. For example:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestPropertySource(locations = "classpath:test.properties")
public class SimpleServiceTest {

    @Autowired
    private SimpleService simpleService;

    @Test
    public void testMethod(){
          ....
          simpleService.testMethod();
          ....
    }


    @Configuration
    public static class Config {


        @Bean
        public SimpleService getSimpleService() {
            return new SimpleService();
        }

        @Bean
        public MockedService getMockedService() {
            return Mockito.mock(MockedService.class);
        } 

     }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM