In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to use java's rest-assured". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use java's rest-assured.
About rest-assured
Rest-assured is a Java DSL that simplifies testing rest services, testing and verifying http services in dynamic languages like ruby or python. Based on java and compatible with groovy dynamic language features, we can test http services like scripting languages.
For example, your http service (http://localhost:8080/lotto/{id}) returns a json as follows:
{
"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]
}
]
}
}
Simply use rest-assured to assert whether your response results are as expected.
Get ("/ lotto") .then () .body ("lotto.lottoId", equalTo (5))
Or you want to assert whether winnerId is 23 and 54:
Get ("/ lotto") .then () .body ("lotto.winners.winnerId", hasItems (23,54))
If it looks simple, have a try?
Rest-assured small-scale trial
Before we run the test case, we need to introduce the maven dependency of * * rest-assured**
Io.rest-assured
Rest-assured
3.0.0
Test
The RestAssured class is the request entry of the entire test framework. A series of static methods are defined inside the class, including our commonly used request types such as POST, GET, PUT, DELETE, OPTIONS, PATCH and HEAD, and request response results.
Can be used for our commonly used verification and assertions.
The RestAssured.get method requests the http service
Response response = RestAssured.get ("http://localhost/greting?id=5");
A series of json conversion methods are defined in the request response result response, and you can easily convert your results to
Direct output of strings such as json
Response.asString ()
Or the corresponding entity bean is converted to a json object or xml.
/ / json
GreetingBean as = response.as (GreetingBean.class)
/ / xml
XmlPath xmlPath = response.xmlPath ()
You can also verify whether the returned result is the result you want.
Response.then (). StatusCode (2000.body ("name", equalTo ("test"))
Looking at this, you may think that the method provided by * * rest-assured** is indeed very simple, but I put httpclient or
Okhttp package can also achieve this effect, I am a programmer, I just like to repeat the wheel, because this can improve my own programming level, then OK, you must build a wheel that is easier to use than it.
For the above http test request can still be simplified, can be implemented in Mini Program, never need a large program.
Step one:
Import static io.restassured.RestAssured.given
Step 2:
Get ("http://localhost/greting?id=5")"
We can send our request using a simple get,post or delete, and we can get the response result to assert whether the result is correct.
Although we are using other people's things, we should also know why and get to the bottom of it. If you are careful enough to open the source code to see the true face, you will find that * * rest-assured** itself is not mysterious, it just makes full use of the feature of java polymorphism and highly inherits and encapsulates the interface. If you look at the implementation of a series of http request methods such as get or post, you will find that all the request body Request,rest-assured itself has redefined it, that is, RequestSpecification, which is only an interface, and its implementation class is TestSpecificationImpl, which encapsulates the standard http request (below, intercepts some of them from the class io.restassured.internal.TestSpecificationImpl), which is implemented in groovy language.
/ * *
* {@ inheritDoc}
, /
Response get (String path, Object... PathParams) {
RequestSpecification.get path, pathParams
}
/ * *
* {@ inheritDoc}
, /
Response post (String path, Object... PathParams) {
RequestSpecification.post path, pathParams
}
/ * *
* {@ inheritDoc}
, /
Response put (String path, Object... PathParams) {
RequestSpecification.put path, pathParams
}
/ * *
* {@ inheritDoc}
, /
Response delete (String path, Object... PathParams) {
RequestSpecification.delete path, pathParams
}
What is groovy? Groovy is an agile development language based on JVM (Java Virtual Machine). It combines many powerful features of Python, Ruby and Smalltalk. Groovy code can be well integrated with Java code, and can also be used to extend existing code.
You can also look at the return result response in this way, and there is also an implementation class called ResponseSpecificationImpl. This fits why we said in the first place that rest-assured is based on java DSL (* DSL is a development language designed for specific tasks *) framework.
Rest-assured advantage
* simple enough, short enough, and quick to write test cases (* it should be the reason why programmers can't find a girlfriend *).
* order control structure (* the simplest structure is this, execute this statement and then execute the form of the next statement *)
* in line with the idea of contract programming (* if the function is called if the precondition is met, then the execution of the function will establish the postcondition *)
Rest-assured system testing
After patiently reading the above, I believe you have an overall understanding of the testing framework, but in real situations it is impossible to use the main function of java to directly call the static functions in RestAssured, because the test cases written in this way are not easy to maintain and are not portable, because today you simply run the test cases before packaging, make sure there are no errors, and then type them into a test package. But after that, there may also be continuous integration of this product (CI server or jenkins, etc.), or the number of users of this product is relatively large. We need to run the script in Jmeter or loaderunner to test the performance. At this point, we want to use * rest-assured* with * Junit* (or some unit testing framework testNG, etc.).
Here are a few common test case scenarios:
The first step is to make sure you have introduced the Junit and rest-assured packages.
And static while introducing the class, as follows:
Import static io.restassured.RestAssured.get
Import static io.restassured.RestAssured.given
Import static io.restassured.RestAssured.post
Import static org.hamcrest.Matchers.*
@ Before
Public void setup () {
RestAssured.baseURI = "http://localhost";
RestAssured.port = 8080
}
Here is the preparation before running the test case using Junit's annotations. Here we configure the ip address and port. Seeing that some students here may want to ask me that my request is based on an one-way https request, we can add it to the setup function:
`RestAssured.config.getSSLConfig () .relaxedHTTPSValidation (); `
This setting means trusting all clients. You can request to the server directly without carrying any trustworthy certificates. If you use OKHttp or httpURLConnection, you may have to take the time to bypass https authentication. You may have a trustworthy certificate on hand. If you want to simulate a real browser environment, you can set it as follows:
RestAssured.config.getSSLConfig () .trustStore (test.truststore, "123456")
I have implemented the certificate-based two-way authentication process in my own native java language and httpclient. [for more information, please see the source code] (https://github.com/strictnerd/LearningSummary/tree/master/src/main/java/com/clq), which has been too concise to be streamlined), and I have written about ten lines of code. If I don't refer to what I wrote before, I may have to open API to see how it is called. But rest-assured did a good package with us as follows:
RestAssured.certificate ("clq.truststore", "123456", "clq.p12", "123456", CertificateAuthSettings.certAuthSettings (). KeyStoreType ("PKCS12"). TrustStoreType ("jks"))
Because the encapsulation of the code is not good enough, which reduces our work efficiency, it is obvious that rest-assured improves our work efficiency and reduces the probability that we may make mistakes in our work.
In fact, it not only does the encapsulation of single and two-way authentication, but also our usual user name and password login, oauth authentication, agent request and so on.
Step two, start our rest service testing
Get request test
@ Test
Public void greetingTest () {
Given (. Param ("name", "clq")
Then (). StatusCode
.body ("id", equalTo (2), "content", containsString ("Hello"))
.when () .get ("/ greeting")
}
The meaning of this long string of sequence control structure code is to give the parameter name, when I send the get request, then you return the response code 200and the id=2,content is hello.
If your rest service request test has some particularity, you can make another declaration in this test case. As follows:
@ Test
Public void greetingTest () {
Try {
RestAssured.requestSpecification = new RequestSpecBuilder () .addCookie ("cookie", "123456") .build ()
Given (. Param ("name", "clq")
Then (). StatusCode
.body ("id", equalTo (2), "content", containsString ("Hello"))
.when () .get ("/ greeting")
} finally {
RestAssured.reset ()
}
}
After using it, remember to reset in finally, as it may affect other test cases. Similarly, let's give an example of post based on json request. (this framework not only supports body parameters based on json format, but also supports our commonly used form forms or xml parameters. )
@ Test
Public void postTest () {
Map map = new HashMap ()
Map.put ("id", 123412)
Map.put ("addr", "zz")
Map.put ("age", Arrays.asList (12dy27 dint 23,41))
Given () contentType (ContentType.JSON)
.body (JSON.toJSONString (map)) .proxy (ProxySpecification.host ("192.168.1.11") .withPort (2010))
Then (). StatusCode
.body ("addr", equalTo ("zz"), "id", equalTo (123412), "age [1]", is (27))
.time (lessThan (1L), TimeUnit.SECONDS)
.when () .post ("/ welcome")
}
For this post request, I have set up a lot of scenarios here, first of all, passing parameters in json in requestBody, and using proxy 192.168.1.11 post 2010. When I send the post request, then return to me the result in the response code 200Magi body as expected (there is a built-in hamcrest package in it, and its main function is to return the result for verification by response). These scenarios are also quite common. For example, my backend needs to add such a function to support the call of the Wechat official account service, but my entire backend service is deployed in the private network. Only Wechat calls the Wechat official account to obtain the openid. This part needs to use the public network, so I set up a proxy server of the public network, so I can request the proxy service based on the http. Only these rest services are allowed to access the public network.
We also have some frequently used scenarios such as file uploads and downloads, which are also supported.
The file is uploaded, and the colleague who is uploading the file supports the transfer of parameters.
@ Test
Public void uploadFile () {
Response post = given () .param ("id", "123456")
.multiPart ("file", new File ("D:/zzrd.jpg"))
.post ("/ file")
Assert.assertEquals ("123456", post.asString ())
}
The file is downloaded as follows:
@ Test
Public void downloadFile () {
Response response = given () .get ("/ export")
Byte [] bytes = response.asByteArray ()
BufferedOutputStream bos = null
Try {
Bos = new BufferedOutputStream (new FileOutputStream (new File ("d:/xxoo.xls")
Bos.write (bytes)
} catch (FileNotFoundException e) {
/ / TODO
E.printStackTrace ()
} catch (IOException e) {
/ / TODO
E.printStackTrace ()
} finally {
Try {
If (bos! = null) {
Bos.close ()
}
} catch (IOException e) {
E.printStackTrace ()
}
}
}
Rest-assured usage scenario
My system testing is very complex, there are form-based, json-based data format, and the use of xml format, some of the returned data structure is also very complex, some interfaces request address or port is not the same, or use the proxy and other functions.
You can use rest-assured directly to solve these practical problems you encounter.
Can I use rest-assured directly in requests for business code?
In fact, I do not recommend this, because I have made a comparison between rest-assured and httpclient on my machine based on my own system, single-threaded testing (* 1000 requests respectively, rest-assured takes 85s and httpclient takes 79s*) and then I have done multithreaded testing myself. No matter how I test it, I come to the conclusion that httpclient is faster than rest-assured. Of course, this may not be accurate, the service is different in different environments, the test results will change accordingly. After all, the bottom layer of rest-assured encapsulates httpclient again, and uses groovy,groovy, although it is a dynamic language, but it is still based on the jvm platform, and finally compiled into class. Personally, groovy has no advantage over other scripting languages such as ruby or python, except that it is executed on the jvm platform and the scripts written are short enough. But when it is used as a test case, the advantage is still very great, because the test case, not an online environment, has no special requirements for performance.
Can I use rest-assured to test the interface when I use springmvc Controller?
As a matter of fact, there is also a corresponding spring-mock-mvc for this rest-assured, but spring is also tested based on spring-test API. If you still use rest-assured, you always feel like you are holding a hammer to find a nail.
The benefits of testing
Testing brings a lot of benefits to our products. Here we just test based on rest API. In unit testing, this is a coarse-grained test. If you want to be more detailed, such as script testing based on H3 database, but now most of our frameworks use jpa, this test can bring us some benefits, but the workload is also considerable. Whether we should conduct some simulation tests based on the H3 in-memory database, we should make our own decisions and not make too many suggestions. As for isolation testing based on mock business logic, when we encounter complex business logic, or in a certain environment, a scenario is difficult to simulate, which can be avoided if we use mock. This kind of testing should or should be done, so let's briefly talk about the obvious benefits of the unit test itself.
First of all, it should be that it is a kind of verification behavior, and has a certain degree of reversibility.
We just write a test case after each function is completed, and we can verify that our function is passed immediately. When one of our modules or a large function passes, we can quickly run all the unit tests based on maven. To ensure that our functionality is tested locally. In fact, in the later stage of development, we look at a certain function or business logic is very unhappy (this is written by someone else), then we can directly modify the function or refactoring, then we can use test cases to ensure that other designs are not destroyed, to put it bluntly, unit testing can give us confidence to improve the design.
Unit test code is more maintainable and, to some extent, can be thought of as a document behavior, but the effect may be better than that of a document.
A set of system, I developed, may be handed over to AA in a few days, 2 years later to CC,CC how to know that the background service system is completely no problem, or how he knows what the purpose of a rest service is. If we write a complete input and output assertion mechanism in our test cases, the code readability of the whole system will be enhanced.
Can improve the quality of the code to some extent.
I also think this is very important. When you finish writing a simple function, you run it and enter some boundary conditions to ensure that the program is runnable. This is necessary, but when you have a problem, usually the process of debugging the code is to make a breakpoint and go inside the code for detailed analysis, and then you have an overall understanding of the business logic you have just completed. at this time, if you find that there is something inappropriate, or code redundancy, you should start to adjust. Especially when you use mock for isolation testing, sometimes you have to decouple to test a scenario (because it makes it easier to test) and unwittingly improve the quality of your code.
Of course, the above are some of the benefits of unit testing, testing should be part of software development, these are undeniable. Some people even put forward TDD, first write test cases, test cases to determine what product code to write, which fully illustrate the importance of unit testing.
So we should not only write test cases, but also write good test cases.
System test coverage is still pitifully low?
In fact, the reason is that the product update iteration needs to occupy the market quickly, or the project is so urgent that there is no time to write test cases. I feel that except for some big cows in the industry, no one can guarantee that there will be no problems at all before testing a piece of their own business code. Besides, it is estimated that there are not many people in the industry who write business code. So I often find some phenomenon is that most people in this case, for rest service interfaces, simply and easily use a httpURLconnection to test all interfaces in turn, and finally test their own test code has a problem, how to ensure the quality of their server code? Some students may be good at using some tools, such as Google's postman or restclient http interface testing tools, directly copy the request, add parameters, run, OK! Some proficient students find that they can also collect them and put the interfaces you added before into a list and continue to use them in the future. To some extent, he has improved our efficiency, but do we have to manually click on the interfaces you added before we go online? we can still talk about the past at first, but in the long run, the efficiency is too low.
Here we are looking at rest-assured in turn, or we develop a test framework for our system, which is usually a logical control code plus assertion. Such a simple code can indeed guarantee the quality of our products and improve our work efficiency.
At this point, I believe you have a deeper understanding of "how to use java's rest-assured". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.