我想使用Junit测试我的Web服务。一旦我们错过了public
修饰符,它就会失败。因此,为了避免在早期阶段出现此类问题,我们想编写Junit测试用例来测试Web服务连接。
我尝试过,但是没有用。
String url = "http://localhost:port/webservice/path";
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet( url );
request.setHeader("username", "user1");
HttpResponse httpResponse =
HttpClientBuilder.create().build().execute(request);
HttpResponse response = client.execute(request);
httpResponse.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
while ((line = rd.readLine()) != null) {
result.append(line);
}
My web service will be like this
@Path("/path")
public interface WebServiceTest
{
//list of services
}
我应该通过Junit测试用例来了解我的呼叫是成功还是失败。 如何执行呢?除Junit之外,还有其他建议,但应该通过Java(否Mockito)进行?
编辑:SOAP和REST Web服务都需要它。
答案 0 :(得分:0)
尝试使用RestAssured。使用这样的方法并传递适当的值。
public static ResponseBody callAPI(String host, String body, String path, String method, Map<String,String> headers){
RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder();
requestSpecBuilder.addHeaders(headers);
requestSpecBuilder.setBody(body);
requestSpecBuilder.setBaseUri(host);
RequestSpecification requetSpecification = requestSpecBuilder.build();
requestSpecBuilder.setContentType(ContentType.JSON);
Response rs = null;
if(method.equals("DELETE")){
rs = RestAssured.given(requetSpecification).when().log().all().delete(path);
}else if(method.equals("POST")){
rs = RestAssured.given(requetSpecification).when().log().all().post(path);
}
return rs.getBody();
}