gpt4 book ai didi

java - 使用@RestClientTest 对 rest 客户端进行 Spring boot 测试

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:02 33 4
gpt4 key购买 nike

我正在使用 spring boot 1.5.8 并想测试我的客户端:

@Component
public class RestClientBean implements RestClient {
private Map<String, RestTemplate> restTemplates = new HashMap<>();

@Autowired
public RestClientBean(RestTemplateBuilder builder, SomeConfig conf) {
restTemplates.put("first", builder.rootUri("first").build();
restTemplates.put("second", builder.rootUri("second").build();
}
}

通过以下测试:

@RunWith(SpringRunner.class)
@RestClientTest(RestClient.class)
public class RestClientTest {
@Autowired
private RestClient client;

@Autowired
private MockRestServiceServer server;

@TestConfiguration
static class SomeConfigFooBarBuzz {
@Bean
public SomeConfig provideConfig() {
return new SomeConfig(); // btw. not sure why this works,
// but this is the only way
// I got rid of the "unable to load
// SomeConfig auto-wire" or something like this :)
// Anyway not my main issue
// EDIT: just realized that the whole
// @TestConfiguration part can be avoided by
// adding SomeConfig.class to the classes in the
// @RestClientTest annotation
}
}

@Before
public void setUp() throws Exception {
server.expect(requestTo("/somePath")) // here an exception is thrown
// (main issue)
.andRespond(withSuccess("<valid json>", MediaType.APPLICATION_JSON));
}
}

异常很明显:

java.lang.IllegalStateException: Unable to use auto-configured 
MockRestServiceServer since MockServerRestTemplateCustomizer has been bound to
more than one RestTemplate

但是是否有可能以某种方式对其进行测试,或者是否不允许在一个客户端类中实例化两个不同的剩余模板?我只需要在某些情况下使用第一个休息模板,在其他一些情况下使用第二个休息模板。

最佳答案

经过几天的调查并通过 GitHub 与 spring 人员进行沟通后,我找到了适合我的解决方案,在这里没有收到答案意味着我的解决方案可能对某些人有值(value):

@RunWith(SpringRunner.class)
@RestClientTest(RestClient.class)
public class RestClientTest {
@Autowired
private RestClient client;

private MockRestServiceServer firstServer;
private MockRestServiceServer secondServer;
private static MockServerRestTemplateCustomizer customizer;

@TestConfiguration
static class RestTemplateBuilderProvider {
@Bean
public RestTemplateBuilder provideBuilder() {
customizer = new MockServerRestTemplateCustomizer();
return new RestTemplateBuilder(customizer);
}
}

@Before
public void setUp() {
Map<RestTemplate, MockRestServiceServer> servers = customizer.getServers();
// iterate and assign the mock servers according to your own strategy logic
}

@Test
public void someTest() {
firstServer.expect(requestTo("/somePath"))
.andRespond(withSuccess("some json body"),
MediaType.APPLICATION_JSON));

// call client

// verify response
}

基本上指定与您在客户端代码中使用的休息模板数量相同的模拟服务器数量,然后指定一个测试配置,为休息构建器提供定制器,以便您的客户端代码的休息模板将通过这个定制的构建 build 者。然后使用定制器将模拟服务器绑定(bind)到创建的其余模板,并根据需要定义对它们的期望。

关于java - 使用@RestClientTest 对 rest 客户端进行 Spring boot 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47538025/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com