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());
}
}
答案 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)