【问题标题】:Override autowired instance with a mock用模拟覆盖自动装配的实例
【发布时间】:2018-09-25 21:08:45
【问题描述】:

ServiceInstance.createInstance 应该在对下面的 URL 进行 PUT 调用时被调用。为了能够测试发送 PUT 请求时是否调用了正确的方法,我想模​​拟调用了该方法的对象(ServiceInstance)。但是,模拟不会覆盖真实实例。我在这个设置中缺少什么?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MySpringBootApplication.class })
@SpyBean(ServiceInstance.class)

public class ServiceTest {

@Autowired
ServiceInstance serviceInstance;

@BeforeClass
public static void setUp() {
    SpringApplication.run(MySpringBootApplication.class, new String[] {});
}

@Test
public void sendPutRequest() throws JSONException, ClientProtocolException, IOException {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPut putRequest = new HttpPut("http://localhost:8080/v2/instances/1");
    //.....

    httpClient.execute(putRequest);
    Mockito.verify(serviceInstance, Mockito.times(1)).createInstance(Mockito.any());

}

}

【问题讨论】:

    标签: java testing mocking mockito spy


    【解决方案1】:

    您可以为测试创建配置文件

    @Profile("test")
    @Configuration
    public class ServiceInstanceConfiguration {
       @Bean
       @Primary
       public ServiceInstance serviceInstance() {
        return Mockito.mock(ServiceInstance.class);
       }
    }
    

    并使用配置文件“test”运行您的测试

    @ActiveProfiles("test")
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { MySpringBootApplication.class })
    public class ServiceTest {
    
        @Autowired
        ServiceInstance serviceInstance;
      //...
    

    【讨论】:

      【解决方案2】:

      因为你没有使用mock,而是使用了spy,所以调用了真实的对象和真实的方法。

      尝试使用 MockBean 注释代替 SpyBean 注释(它在 Spring 上下文中模拟 bean)

      Example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        • 2012-02-17
        相关资源
        最近更新 更多