简体   繁体   English

使用 Spring 进行 Mocking

[英]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?我在 Spring 和 mockito 中使用 junit。当我们使用 Spring 时,我们必须加载 spring 配置文件。但是通过这样做,我们获得了所有真实对象。mockito 在这种情况下扮演什么角色?

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.如果我在使用 mockito 的测试用例中使用这个 @ContextConfiguration(locations = {"classpath:/application-context.xml"}) ,我将从 applicationContext.xml 获取对象,这些对象将是真实的对象。

how can mockito be utilized here如何在这里使用 mockito

You don't have to use Spring to unit test your code.您不必使用 Spring 对代码进行单元测试。 You can use Mockito @InjectMocks to inject dependencies into your class under test.您可以使用 Mockito @InjectMocks将依赖项注入被测类中。

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.如果您想使用 Spring 进行单元测试,您可以使用 Spring 中的@ContextConfiguration注释,并在适当的情况下使用@ContextConfiguration在测试本身中定义配置。 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);
        } 

     }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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