简体   繁体   English

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

[英]Best way to test a REST service in java

  1. What is the best way to test REST services in Java? 在Java中测试REST服务的最佳方法是什么? What approaches and tool set do developers usually take? 开发人员通常采用哪些方法和工具集?

  2. Also if you are writing rest clients that call into third party REST services. 此外,如果您正在编写调用第三方REST服务的其他客户端。 What is the best way to test REST clients. 测试REST客户端的最佳方法是什么? Do you have JUnit tests that communicate with a third party REST service. 您是否拥有与第三方REST服务通信的JUnit测试。 You could run into the risk of service not being available/or production REST service cannot be access without certain credentials. 您可能会遇到服务无法使用的风险/或生产REST服务无法访问而无需某些凭据。

1. What is the best way to test REST services in Java? 1.在Java中测试REST服务的最佳方法是什么? What approaches and tool set do developers usually take? 开发人员通常采用哪些方法和工具集?

  • 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. 接下来,您将发布REST服务并尝试使用某种类型的http客户端访问RESTful方法。
    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. 如果是基于GET或PUT的请求,请输入网址和信息。 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. 如果它在浏览器中工作,它应该与您选择的任何支持HTTP的客户端执行类似的操作。

2. Also if you are writing rest clients that call into third party REST services. 2.此外,如果您正在编写调用第三方REST服务的其他客户端。 What is the best way to test REST clients. 测试REST客户端的最佳方法是什么? Do you have JUnit tests that communicate with a third party REST service. 您是否拥有与第三方REST服务通信的JUnit测试。 You could run into the risk of service not being available/or production REST service cannot be access without certain credentials. 您可能会遇到服务无法使用的风险/或生产REST服务无法访问而无需某些凭据。

  • You can generally use any sort of Http Client library you wish based on the language you are using. 您通常可以根据您使用的语言使用任何类型的Http Client库。 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. 通过测试REST客户端来注意的主要缺陷是确保捕获REST服务返回的响应并检查状态。 If it is good, you will get a 200, server error 500, etc. etc. 如果它是好的,你将获得200,服务器错误500等。等。
    I recommend taking a look at W3C or Wikipedia status code information https://en.wikipedia.org/wiki/List_of_HTTP_status_codes or https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html . 我建议您查看W3C或Wikipedia状态代码信息https://en.wikipedia.org/wiki/List_of_HTTP_status_codeshttps://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. 这应该在服务的api文档中提供。 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. api还应解释需要通过标头或作为REST调用的参数传递的任何类型的凭证或要求。

Understanding how REST works and HTTP in general would be good starting points. 了解REST如何工作以及HTTP通常是一个很好的起点。

There are several ways to test REST API, depends on your needs: 有几种方法可以测试REST API,具体取决于您的需求:

  • Jersey Test - you can execute and test REST API calls with in-memory HTTP server. Jersey Test - 您可以使用内存中的HTTP服务器执行和测试REST API调用。 You'll need to mock your code - use Mockito ( Jersey 1.19 Test configuration - mock classes ) or in-memory testing database. 您需要模拟您的代码 - 使用MockitoJersey 1.19测试配置 - 模拟类 )或内存测试数据库。
  • Rest Assured - the main drawback is that you need to run REST API project separately/individually from tests ( RestAssured testing without running Tomcat ) Rest Assured - 主要缺点是您需要单独/单独地从测试运行REST API项目( RestAssured测试而不运行Tomcat
  • Tools with UI - SOAP UI or Postman 带UI的工具 - SOAP UI邮递员
  • Swagger - generates interactive documentation - web page where you execute REST methods with prepared data according annotated methods in a code. Swagger - 生成交互式文档 - 您可以根据代码中的注释方法使用准备好的数据执行REST方法的Web页面。
  • Use Spring Boot for developing REST services. 使用Spring Boot开发REST服务。 It has various tools for testing which you can use out of the box without excessive configuration. 它有各种测试工具,您可以在没有过多配置的情况下开箱即用。

You can create a REST Service mock using SoapUI . 您可以使用SoapUI创建REST服务模拟。 Also, if you needed to run this test through maven, you can use soapui-maven-plugin to instanciate do soapui service automatically 此外,如果您需要通过maven运行此测试,您可以使用soapui-maven-plugin自动执行soapui服务

I suggest that you take a look at REST Assured for automated testing of REST services. 我建议您查看REST Assured以自动测试REST服务。 The following example is copied from it's web page : 以下示例从其网页复制:

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 started and usage guides 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 Application that I wrote a couple of years ago interesting. 如果您使用Spring Boot实现了服务器应用程序,那么您可能还会发现几年前我写的有关集成测试Spring Boot应用程序的博客文章。 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. 它显示了Spring Boot测试支持如何启动嵌入式Web服务器并在针对REST API执行基于REST Assured的测试之前将应用程序部署到该服务器。 In other words, neither do you have to manually start a web server, nor do you need to re-deploy the app between tests. 换句话说,您既不必手动启动Web服务器,也不需要在测试之间重新部署应用程序。 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. 事实上,您甚至不必在代码更改之间创建.war或.jar文件,以验证REST API更改。

For part 2 in your question, the correct answer depends on various factors. 对于问题的第2部分,正确的答案取决于各种因素。 You would want to consider both the resolution of the mocking and the time spent writing and maintaining the tests. 您可能需要考虑模拟的分辨率以及编写和维护测试所花费的时间。

Client library 客户端库

The choice of HTTP-client will affect your options - some klients (like Spring RestTemplate) offer built-in mocking support. HTTP客户端的选择会影响您的选择 - 一些klients(如Spring RestTemplate)提供内置的模拟支持。 If you have a service definition like a swagger or RAML file, you'd want to generate the client. 如果您有像swagger或RAML文件这样的服务定义,那么您需要生成客户端。

Project configuration 项目配置

The most thorough way is to actually let the application make HTTP calls to real endpoints, involving the full stack. 最彻底的方法是实际让应用程序对真实端点进行HTTP调用,涉及完整堆栈。 If so, configure your project so that the client URLs are injected in a per-environment (or profile) fashion. 如果是这样,请配置项目,以便以每个环境(或配置文件)方式注入客户端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 (ie on jenkins). 服务在localhost端口上进行模拟 - 最好是随机选择,以便可以进行并行测试(即在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). 虽然其他工具直接在类服务定义上工作,但基本上你可以使用像Mockito这样的工具来直接模拟对象(但是包装在真正的端点中)。 This should be less error prone, but requires the classes to be present (as test dependencies). 这应该不易出错,但需要存在类(作为测试依赖性)。 I've written a tool like that, for comparison. 为了比较,我写了一个这样的工具

Karate is a framework that has been designed from the ground up for testing web-service API-s. Karate是一个从头开始设计用于测试Web服务API的框架。 It has its own tag on Stack Overflow. 它在Stack Overflow上有自己的标记

There is a detailed comparison with REST-assured here . 有一个与保证的REST了详细的对比在这里 It has also been listed as one of the top 5 open-source API testing tools, just within 6 months of its release. 它也被列为五大开源API测试工具之一,仅在发布后的6个月内。

Disclaimer: I happen to be the author of Karate. 免责声明:我恰好是空手道的作者。

Karate is a framework that has been designed from the ground up for testing web-service API-s. Karate是一个从头开始设计用于测试Web服务API的框架。 It has its own tag on Stack Overflow. 它在Stack Overflow上有自己的标记

There is a detailed comparison with REST-assured here . 有一个与保证的REST了详细的对比在这里 It has also been listed as one of the top 5 open-source API testing tools, just within 6 months of its release. 它也被列为五大开源API测试工具之一,仅在发布后的6个月内。

Disclaimer: I happen to be the author of Karate. 免责声明:我恰好是空手道的作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM