我想在 Spring 启动集成测试中创建 Bean 之前模拟服务器



我正在用 spring-boot 编写集成测试。 我的一个豆子正在使用UrlResource("http://localhost:8081/test"(来创建它。 我想创建一个模拟服务器,它将为上面的 url 提供模拟响应。 但是我希望在初始化任何 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;
}
}

使用上述方法我得到 " java.net.ConnectException: 连接被拒绝(连接被拒绝(" 错误,因为它无法访问 http://localhost:8081/test 终结点。

使用@InjectMocks

参考:文档和示例解释。

我已经通过在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;
}
}

最新更新