java - 如何通过 Junit 测试 Web Service 调用

标签 java web-services junit

我想使用 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 服务。

最佳答案

尝试使用 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();

    }

关于java - 如何通过 Junit 测试 Web Service 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56778568/

相关文章:

java - Sentinel 无法在 Java while 循环中工作;和 printwriter 不写入文本文件

java.security.AccessControlException : access denied ("java.net.SocketPermission" "smtp.gmail.com" "resolve")

web-services - 通用 SOAP 客户端工具

java - 如何使用 Junit 监视 Java 中的方法?

java - 如何使用 JUnit 测试 Java 中的任何输出

java - 构造函数调用是否必须是构造函数中的第一条语句?

java - 如何加载本地存储的页面到WebView控件?

c# - 如何将 wcf 服务添加到现有类库

java - 获取 com.sun.xml.wss.XWSSecurityException 的 NoClassDefFoundError

java - 测试我的 Maven 库与 Android 的兼容性