1. Overview
1.概述
In this article, we’ll have a look at the Hoverfly Java library – which provides an easy way of creating real API stubs/simulations.
在这篇文章中,我们将看看HoverflyJava库–它提供了一种创建真实API存根/模拟的简便方法。
2. Maven Dependencies
2.Maven的依赖性
To use Hoverfly, we need to add a single Maven dependency:
要使用Hoverfly,我们需要添加一个Maven依赖项。
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>0.8.1</version>
</dependency>
The newest version can be found here.
最新的版本可以在这里找到。
3. Simulating an API
3.模拟一个API
First, we’ll configure Hoverfly to run in the simulation mode. The simplest way to define a simulation is by using a DSL.
首先,我们将配置Hoverfly在模拟模式下运行。定义模拟的最简单方法是使用DSL。
Let’s start with a simple example by instantiating the HoverflyRule instance:
让我们从一个简单的例子开始,将HoverflyRule实例化。
public static final HoverflyRule rule
= HoverflyRule.inSimulationMode(dsl(
service("http://www.baeldung.com")
.get("/api/courses/1")
.willReturn(success().body(
jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))));
The SimulationSource class provides a dsl method for initiating the API definition. Also, HoverflyDSL‘s service method allows us to define an endpoint and associated request paths.
SimulationSource类提供了一个dsl方法来启动API定义。此外,HoverflyDSL的service方法允许我们定义一个端点和相关的请求路径。
Then we call willReturn to state which response we want to get in return. We also used success method of ResponseBuilder to set response status and body.
然后我们调用willReturn来说明我们想得到哪种响应的回报。我们还使用ResponseBuilder的success方法来设置响应状态和正文。
4. Using JUnit for Testing
4.使用JUnit进行测试
Stubbed API can be easily tested using JUnit.
存根的API可以很容易地使用JUnit进行测试。
Let’s create a simple test sending an HTTP request and see if it reaches the endpoint:
让我们创建一个简单的测试,发送一个HTTP请求,看看它是否到达端点。
responseEntity<String> courseResponse
= restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
We used Spring Web module’s RestTemplate class instance to send an HTTP request.
我们使用Spring Web模块的RestTemplate类实例来发送一个HTTP请求。
5. Adding Delays
5.添加延时
Delays can be added globally, for particular HTTP method, or for a specific API call.
可以在全局、特定的HTTP方法或特定的API调用中添加延迟。
Here is the example code setting delay on requests with POST method:
下面是设置POST方法请求的延迟的示例代码。
SimulationSource.dsl(
service("http://www.baeldung.com")
.post("/api/courses")
.willReturn(success())
.andDelay(3, TimeUnit.SECONDS)
.forMethod("POST")
)
6. Request Matcher
6.请求匹配器
HoverflyMatchers factory class provides several matchers including exactMatch and globMatch for URLs. For HTTP body it provides.
HoverflyMatchers工厂类提供了几个匹配器,包括exactMatch和globMatch用于URLs。对于HTTP正文,它提供了。
For HTTP bodies it provides JSON/XML exact match and JSONPath/XPath matches.
对于HTTP主体,它提供JSON/XML精确匹配和JSONPath/XPath匹配。
By default, the exactMatch matcher is used for both URL and body matching.
默认情况下,exactMatch匹配器被用于URL和正文匹配。
Here is example use of different matchers:
下面是使用不同匹配器的例子。
SimulationSource.dsl(
service(matches("www.*dung.com"))
.get(startsWith("/api/student"))
.queryParam("page", any())
.willReturn(success())
.post(equalsTo("/api/student"))
.body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}")))
.willReturn(success())
.put("/api/student/1")
.body(matchesJsonPath("$.name"))
.willReturn(success())
.post("/api/student")
.body(equalsToXml("<student><id>2</id><name>John</name></student>"))
.willReturn(success())
.put("/api/student/2")
.body(matchesXPath("/student/name"))
.willReturn(success()));
)
In this example, matches method checks URL with globMatch that allows wildcard search.
在这个例子中,matches方法用允许通配符搜索的globMatch检查URL。
Then startsWith checks if the request path starts with “/api/student“. We used any matcher to allow all possible values in page query parameter.
然后startsWith 检查请求路径是否以”/api/student“开始。我们使用any匹配器来允许页面查询参数中所有可能的值。
The equalsToJson matcher makes sure that the body payload matches the exact JSON given here. The matchesJsonPath method for checking with an element at particular JSON Path exists or not.
equalsToJsonmatcher确保主体的有效载荷与这里给出的JSON完全匹配。matchesJsonPath 方法用于检查特定JSON路径的元素是否存在。
Similarly, equalsToXml matches the XML given in request body with the one given here. The matchesXPath matches a body with an XPath expression.
同样,equalsToXml将请求正文中给出的XML与这里给出的XML进行匹配。matchesXPath用一个XPath表达式来匹配body。
7. Conclusion
7.结语
In this quick tutorial, we discussed the usage of Hoverfly Java library. We looked into simulating HTTP services, DSL for configuring endpoints, adding delays and use of request matchers. We also looked into testing these services using JUnit.
在这个快速教程中,我们讨论了Hoverfly Java库的用法。我们研究了模拟HTTP服务、配置端点的DSL、添加延迟和使用请求匹配器。我们还研究了使用JUnit测试这些服务。
As always, code snippets, as always, can be found over on GitHub.
一如既往,代码片段,可以在GitHub上找到过的代码片段。