我正在使用spring boot并希望创建和测试Http服务。 http服务如下:
@Service
public class HttpService {
private Client client;
@Autowired
public HttpService(Client client) {
this.client = client;
}
<T> T get(String url, MultivaluedMap params, Class<T> type) {
ClientResponse response =
client.resource(url)
.queryParams(params)
.accept(MediaType.APPLICATION_JSON_TYPE)
.type(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
return response.getEntity(type);
}
}
我的测试如下:
public class HttpServiceTests {
private StubServer server;
@Before
public void start() {
server = new StubServer().run();
RestAssured.port = server.getPort();
}
@After
public void stop() {
server.stop();
}
@Test
public void answerWith200() {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getClasses().add(JacksonJaxbJsonProvider.class);
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
HttpService httpService = new HttpService(client);
whenHttp(server).match(get("http://test.com")).then(status(HttpStatus.OK_200), stringContent("all ok"));
String url = "http://test.com";
String response = httpService.get(url, new MultivaluedMapImpl(), String.class);
Assert.assertEquals("all ok", response);
}
}
运行测试时,实际响应是:
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.11.13</center>
</body>
</html>
有谁知道为什么会这样?当我尝试使用 Jadler 库时,我也得到了同样的响应。
答案 0 :(得分:0)
这是因为您的客户端遇到了一些Nginx服务器而不是模拟框架启动的服务。
更仔细地检查restito examples,看看哪些网址需要传递到您的客户端,以便它与Restito服务器而不是某个真实的应用程序进行交互。
另请注意,您不需要将协议和域名传递到whenHttp(server).match(get("..."))
。