在 Java 中测试 REST 服务的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38382204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:16:00  来源:igfitidea点击:

Best way to test a REST service in java

javaweb-servicesrest

提问by serah

  1. What is the best way to test REST services in Java? What approaches and tool set do developers usually take?

  2. Also if you are writing rest clients that call into third party REST services. What is the best way to test REST clients. Do you have JUnit tests that communicate with a third party REST service. You could run into the risk of service not being available/or production REST service cannot be access without certain credentials.

  1. 在 Java 中测试 REST 服务的最佳方法是什么?开发人员通常采用哪些方法和工具集?

  2. 此外,如果您正在编写调用第三方 REST 服务的 REST 客户端。测试 REST 客户端的最佳方法是什么。您是否有与第三方 REST 服务通信的 JUnit 测试。您可能会遇到服务不可用/或生产 REST 服务在没有某些凭据的情况下无法访问的风险。

采纳答案by matsev

I suggest that you take a look at REST Assured for automated testing of REST services. The following example is copied from it's web page:

我建议您查看 REST Assured 以进行 REST 服务的自动化测试。以下示例是从其网页复制的:

For example if your HTTP server returns the following JSON at “http://localhost:8080/lotto/{id}”:

例如,如果您的 HTTP 服务器在“ http://localhost:8080/lotto/{id}”处返回以下 JSON :

{
   "lotto":{
      "lottoId":5,
      "winning-numbers":[2,45,34,23,7,5,3],
      "winners":[
         {
            "winnerId":23,
            "numbers":[2,45,34,23,3,5]
         },
         {
            "winnerId":54,
            "numbers":[52,3,12,11,18,22]
         }
      ]
   }
}

You can easily use REST Assured to validate interesting things from response:

您可以轻松地使用 REST Assured 从响应中验证有趣的事情:

@Test public void
lotto_resource_returns_200_with_expected_id_and_winners() {

    when().
            get("/lotto/{id}", 5).
    then().
            statusCode(200).
            body("lotto.lottoId", equalTo(5), 
                 "lotto.winners.winnerId", containsOnly(23, 54));

}

See the getting startedand usageguides for more information.

有关更多信息,请参阅入门使用指南。



If you have implemented your server app using Spring Boot, you may also find the blog post about Integrating Testing a Spring Boot Applicationthat I wrote a couple of years ago interesting. It shows how Spring Boot test support starts an embedded web server and deploys the application to it before executing REST Assured based tests against the REST API. In other words, neither do you have to manually start a web server, nor do you need to re-deploy the app between tests. As a matter of fact, you do not even have to create a .war or .jar file between your code changes in order to validate REST API changes.

如果您已经使用 Spring Boot 实现了您的服务器应用程序,您可能还会发现我几年前写的关于集成测试 Spring Boot 应用程序的博客文章很有趣。它展示了 Spring Boot 测试支持如何在针对 REST API 执行基于 REST Assured 的测试之前启动嵌入式 Web 服务器并将应用程序部署到它。换句话说,您既不需要手动启动 Web 服务器,也不需要在测试之间重新部署应用程序。事实上,您甚至不必在代码更改之间创建 .war 或 .jar 文件来验证 REST API 更改。

回答by Just Lick It

1. What is the best way to test REST services in Java? What approaches and tool set do developers usually take?

1. 在 Java 中测试 REST 服务的最佳方法是什么?开发人员通常采用哪些方法和工具集?

  • You can test your rest services by first testing the actual code and functionality of the service itself and make sure it is functioning properly using any unit testing library applicable to your project. Next, you would publish the REST service and try accessing the RESTful methods using a http client of some sort.
    Generally, the easiest way is just a plain old browser. Type in the url and information if it is a GET or PUT based request. If it is a post, you can use browser plugins or dev tools to help add data to the body of the request or header as needed and validate you are getting the response you expect. If it works in a browser, it should perform similarly with any HTTP capable client you choose.
  • 您可以通过首先测试服务本身的实际代码和功能来测试您的休息服务,并使用适用于您的项目的任何单元测试库确保它正常运行。接下来,您将发布 REST 服务并尝试使用某种 http 客户端访问 RESTful 方法。
    通常,最简单的方法就是使用普通的旧浏览器。如果是基于 GET 或 PUT 的请求,请输入 url 和信息。如果是帖子,您可以使用浏览器插件或开发工具来帮助根据需要将数据添加到请求或标头的正文中,并验证您是否获得了预期的响应。如果它在浏览器中工作,它应该在您选择的任何支持 HTTP 的客户端上执行类似的操作。

2. Also if you are writing rest clients that call into third party REST services. What is the best way to test REST clients. Do you have JUnit tests that communicate with a third party REST service. You could run into the risk of service not being available/or production REST service cannot be access without certain credentials.

2.此外,如果您正在编写调用第三方 REST 服务的 REST 客户端。测试 REST 客户端的最佳方法是什么。您是否有与第三方 REST 服务通信的 JUnit 测试。您可能会遇到服务不可用/或生产 REST 服务在没有某些凭据的情况下无法访问的风险。

  • You can generally use any sort of Http Client library you wish based on the language you are using. The main pitfall to look out for with testing of a REST client is to make sure you are capturing the Response returned by the REST service and checking the status. If it is good, you will get a 200, server error 500, etc. etc.
    I recommend taking a look at W3C or Wikipedia status code information https://en.wikipedia.org/wiki/List_of_HTTP_status_codesor https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
    Further, you should understand the types of responses that are possible to be returned from the particular service. This should be available in the api documentation for the service. The api should also explain any sort of credentials or requirements that need to be passed through the header or as a parameter to the REST call.
  • 您通常可以根据您使用的语言使用任何类型的 Http 客户端库。测试 REST 客户端时要注意的主要陷阱是确保您正在捕获 REST 服务返回的响应并检查状态。如果它是好的,你会得到 200,服务器错误 500 等等。
    我建议看看 W3C 或维基百科状态代码信息https://en.wikipedia.org/wiki/List_of_HTTP_status_codeshttps://www .w3.org/Protocols/rfc2616/rfc2616-sec10.html
    此外,您应该了解可能从特定服务返回的响应类型。这应该在服务的 api 文档中可用。api 还应该解释需要通过标头传递或作为参数传递给 REST 调用的任何类型的凭据或要求。

Understanding how REST works and HTTP in general would be good starting points.

了解 REST 的工作原理和一般的 HTTP 将是一个很好的起点。

回答by Felipe Martinez

You can create a REST Service mock using SoapUI. Also, if you needed to run this test through maven, you can use soapui-maven-plugin to instanciate do soapui service automatically

您可以使用SoapUI创建 REST 服务模拟。另外,如果你需要通过maven运行这个测试,你可以使用soapui-maven-plugin来自动实例化dosoapui服务

回答by Justas

There are several ways to test REST API, depends on your needs:

有多种方法可以测试 REST API,具体取决于您的需求:

回答by ThomasRS

For part 2 in your question, the correct answer depends on various factors. You would want to consider both the resolution of the mocking and the time spent writing and maintaining the tests.

对于问题中的第 2 部分,正确答案取决于各种因素。您可能需要考虑模拟的解决方案以及编写和维护测试所花费的时间。

Client library

客户端库

The choice of HTTP-client will affect your options - some klients (like Spring RestTemplate) offer built-in mocking support. If you have a service definition like a swagger or RAML file, you'd want to generate the client.

HTTP 客户端的选择会影响您的选择——一些客户端(如 Spring RestTemplate)提供内置的模拟支持。如果你有一个像 swagger 或 RAML 文件这样的服务定义,你会想要生成客户端。

Project configuration

项目配置

The most thorough way is to actually let the application make HTTP calls to real endpoints, involving the full stack. If so, configure your project so that the client URLs are injected in a per-environment (or profile) fashion.

最彻底的方法是实际让应用程序对真正的端点进行 HTTP 调用,涉及整个堆栈。如果是这样,请配置您的项目,以便以每个环境(或配置文件)的方式注入客户端 URL。

Mock endpoints

模拟端点

You want mocking per unit test. No 'deployable mocks' which serve multiple unit-tests. Services are mocked on a localhost port - preferably randomly selected so that parallell testing is possible (i.e. on jenkins).

你想要模拟每个单元测试。没有服务于多个单元测试的“可部署模拟”。服务在本地主机端口上模拟 - 最好是随机选择的,以便可以进行并行测试(即在 jenkins 上)。

Mock data

模拟数据

To save time, for deep data structures, it is very desirable that mock data is read from a file, rather than constructed programmatically. Files are much easier to work with, especially if you enable request/response logging, fixing bugs and so is faster.

为了节省时间,对于深度数据结构,非常希望从文件中读取模拟数据,而不是以编程方式构造。文件更容易使用,特别是如果您启用请求/响应日志记录、修复错误等速度更快。

Mocking

嘲讽

Some frameworks are loosely coupled to the service, as in they are strictly not aware of the nature of the service. Typically you'd mock a respons at some path which is coded in the unit test. This is like Wiremock and most of the test frameworks I've seen.

一些框架与服务松散耦合,因为它们完全不了解服务的性质。通常,您会在单元测试中编码的某个路径上模拟响应。这就像 Wiremock 和我见过的大多数测试框架。

Whereas other tools work directly on class service definitions, basically you'd use a tool like Mockito to mock an object directly (but wrapped in a real endpoint). This should be less error prone, but requires the classes to be present (as test dependencies). I've written a toollike that, for comparison.

而其他工具直接在类服务定义上工作,基本上你会使用像 Mockito 这样的工具来直接模拟一个对象(但包装在一个真正的端点中)。这应该不太容易出错,但需要存在类(作为测试依赖项)。我写了一个这样的工具,作为比较。

回答by Peter Thomas

Karateis a framework that has been designed from the ground up for testing web-service API-s. It has its own tagon Stack Overflow.

Karate是一个从头开始设计用于测试 Web 服务 API 的框架。它在 Stack Overflow 上有自己的标签

There is a detailed comparison with REST-assured here. It has also been listed as one of the top 5open-source API testing tools, just within 6 months of its release.

有一个与REST-放心了详细的对比在这里。它也被列为5大开源 API 测试工具之一,仅在发布后的 6 个月内。

Disclaimer: I happen to be the author of Karate.

免责声明:我碰巧是空手道的作者。

回答by Peter Thomas

Karateis a framework that has been designed from the ground up for testing web-service API-s. It has its own tagon Stack Overflow.

Karate是一个从头开始设计用于测试 Web 服务 API 的框架。它在 Stack Overflow 上有自己的标签

There is a detailed comparison with REST-assured here. It has also been listed as one of the top 5open-source API testing tools, just within 6 months of its release.

有一个与REST-放心了详细的对比在这里。它也被列为5大开源 API 测试工具之一,仅在发布后的 6 个月内。

Disclaimer: I happen to be the author of Karate.

免责声明:我碰巧是空手道的作者。