【发布时间】:2018-05-12 06:58:55
【问题描述】:
我正在使用 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
但是是否可以通过某种方式对其进行测试,或者是否不允许在一个客户端类中实例化两个不同的其余模板? 我只是需要在某些情况下使用第一个 rest 模板,而在其他一些情况下使用第二个。
【问题讨论】:
标签: java resttemplate spring-boot-test mockrestserviceserver