我得到了这样的实现:
@Service
class AbcService {
private final RestClient client;
public AbcService(@Value("url") final String url) {
this.restClient = RestClient.builder().baseUrl(url).build();
}
String getPlace(String id) {
return restClient.get()
.uri("places/{id}", id)
.retrieve()
.body(String.class);
}
}
我尝试使用
MockRestServiceServer
进行测试,但它对我不起作用 - 我有错误
java.lang.IllegalStateException: Unable to use auto-configured MockRestServiceServer since a mock server customizer has not been bound to a RestTemplate or RestClient
测试
@RestClientTest(AbcService.class)
class AbcServiceTest {
@Autowired
AbcService instance;
@Autowired
MockRestServiceServer server;
@BeforeEach
void setup() {
System.setProperty("url", "server123");
}
@Test
void test() {
server
.expect(requestTo("places/id1"))
.andRespond(withSuccess("string", APPLICATION_JSON));
assertEquals("string", instance.getPlace("id1"));
}
}
你能帮我吗?
我建议为 RestClient 客户端创建一个 bean; 当启动应用程序时正确加载 bean 时。
@Bean
RestClient client() {
return RestClient.builder().baseUrl(url).build();
}
并且直接使用service中的bean,而不是在service类中设置url