我想使用selenium(java)自动执行REST API,这可能吗?如果标题和正文部分采用json格式
答案 0 :(得分:0)
在Java中,您可以使用https://www.mkyong.com/java/apache-httpclient-examples/的ApacheHttpClient
例如,ApacheHttpClientPost中的方法可能是这样的:
public static String post(String tokenMobile, String method, String version, String body) throws Exception{
try {
HttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder builder = new URIBuilder();
builder.setScheme("https").setHost(host).setPath(method)
.setParameter("", ""); //Params
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpPost postRequest = new HttpPost(httpget.getURI()); //Header
postRequest.addHeader("Content-Type", "application/json");
postRequest.addHeader("version", version);
postRequest.addHeader("Authorization", "Bearer "+tokenMobile);
StringEntity input = new StringEntity(body); //Body in json
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
StringBuilder stringBuilder = new StringBuilder();
outputs = stringBuilder.append(output).toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outputs;
}
答案 1 :(得分:0)
Selenium是用于UI或e2e测试用例自动化的工具。您可以将Selenium测试用例与API测试用例集成在一起,但这始终不是一个好主意。
如果要自动执行API测试用例,请尝试使用Rest-Assured, Postman, HTTPClient
之类的方法。