[英]I want to mock a server before bean creation in spring boot integration test
我在spring-boot中編寫集成測試。 我的其中之一是使用UrlResource(“ http:// localhost:8081 / test ”)進行創建。 我想創建一個模擬服務器,它將通過模擬響應來提供上述網址。 但是我希望在初始化任何bean之前創建此模擬服務器,因為在初始化bean之前,模擬服務器應可用於處理請求。
我已經嘗試在@TestConfiguration中使用MockRestServiceServer
以下是失敗的偽代碼:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestApiGatewayApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {
}
@TestConfiguration
class TestConfig {
@Bean
public RestTemplateBuilder restTemplateBuilder() {
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
String mockKeyResponse = "{\"a\":\"abcd\"}";
mockServer.expect(requestTo("http://localhost:8081/test"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(mockKeyResponse, MediaType.TEXT_PLAIN));
RestTemplateBuilder builder = mock(RestTemplateBuilder.class);
when(builder.build()).thenReturn(restTemplate);
return builder;
}
}
}
以下是用於創建要測試的bean的示例代碼。
@Configuration
public class BeanConfig {
@Bean
public SampleBean sampleBean(){
Resource resource = new UrlResource("");
// Some operation using resource and create the sampleBean bean
return sampleBean;
}
}
使用上述方法,由於無法訪問http:// localhost:8081 / test端點,因此出現“ java.net.ConnectException:連接被拒絕(連接被拒絕)”錯誤。
我已經通過在testConfiguration中創建MockServiceServer解決了此問題。 示例代碼如下。
@TestConfiguration
static class TestConfig {
@Bean
public RestTemplateBuilder restTemplateBuilder() {
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
String mockKeyResponse = "{\"a\":\"abcd\"}";
mockServer.expect(requestTo("http://localhost:8081/test"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(mockKeyResponse, MediaType.TEXT_PLAIN));
RestTemplateBuilder builder = mock(RestTemplateBuilder.class);
when(builder.build()).thenReturn(restTemplate);
return builder;
}
}
然后,在需要使用該類的BeanConfig類中,我已使用構造函數注入進行了自動裝配,以便在創建BeanConfig類的bean之前創建RestTemplate。 以下是我的操作方式。
@Configuration
public class BeanConfig {
private RestTemplate restTemplate;
public BeanConfig(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Bean
public SampleBean sampleBean(){
Resource resource = new UrlResource("");
// Some operation using resource and create the sampleBean bean
return sampleBean;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.