用模拟覆盖自动装配的实例

时间:2018-09-25 21:08:46

标签: java testing mocking mockito spy

当对下面的URL进行PUT调用时,应该调用

ServiceInstance.createInstance。为了能够测试在发送PUT请求时是否调用了正确的方法,我想模​​拟具有被调用方法的object(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());

}

}

2 个答案:

答案 0 :(得分:0)

您可以创建测试配置文件

@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;
  //...

答案 1 :(得分:0)

这是因为您没有使用模拟,而是使用了间谍,所以调用了真实的对象和真实的方法。

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

Example