In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the Java interface automation testing framework design of the Get request method and test example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
1.Get request API example
The browser opens the URL https://reqres.in, and then drops down one screen, and we can see the API example of this website. Let's take a look at the get interface that shows the user.
Through this diagram, we can get this information.
1) website host address: https://reqres.in/
2) the user displays the request by: Get
3) the url of the API is: / api/users
4) the response status code of the API is 200, and you can also see the JSON content of the response body.
After obtaining the above interface information, we will test it on the local postman. If there is no postman, please install a graphical interface tool similar to postman that can do manual testing of the interface, such as jmeter.
For this interface, we have passed the postman manual test and found that the result is the same as that provided by the website, indicating that the get request interface test passed. So what do we need to do if we want to do it through Java code? Next, it is the key content of this article.
two。 Code process
In the previous article, we introduced the process of building the basic environment, here, followed by the previous environment to gradually complete the design and testing process of an Get request.
2.1 Design profile
Our sequence is to teach you the purpose of designing an interface automation testing framework, so some of the ways we design and organize the project structure need to refer to the thinking of the framework. Write a configuration file, very simple, the meaning is to facilitate the testing of interfaces in multiple environments. In our work, a project, divided into test environment, pre-release environment and online production environment, these three environments, the interface must be the same, but the server address is different, so our framework design needs to support writing a set of interface test cases. You can run the same in three sets of environments.
Create a new package under src/main/java: com.qa.config, and then create a new config.properties file under the new package with the following contents.
Then create a new package under src/main/java: com.qa.base, and create a new TestBase.java. As the parent class of all interface request tests, this class needs to inherit this parent class. For now, we will write a constructor to load and read the properties file.
The TestBase.java code is as follows:
Package com.qa.base; import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;public class TestBase {public Properties prop; / / write a constructor public TestBase () {try {prop = new Properties () FileInputStream fis = new FileInputStream (System.getProperty ("user.dir") + "/ src/main/java/com/qa/config/config.properties"); prop.load (fis);} catch (FileNotFoundException e) {e.printStackTrace () } catch (IOException e) {e.printStackTrace ();}
Here to review the role of the constructor, above we write the code to load the configuration file in the empty parameter construction, the advantage is that each initialization of the object of this class will execute the constructor code, that is, to read the configuration file. As to whether the above configuration file paths are spliced correctly, you can create a new class of the main method and execute the print statement: System.out.println (System.getProperty ("user.dir"))
At present, the project structure diagram is as follows
2.2 Get request method code implementation
Create a new package under src/main/java: com.qa.restclient, and then create a new RestClient.java file. Here is the specific code that implements the get request, and gets the corresponding status code and response header information, as well as the json content of the response body.
Package com.qa.restclient; import java.io.IOException;import java.util.HashMap;import org.apache.http.Header;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject Public class RestClient {/ / 1.Get request method public void get (String url) throws ClientProtocolException, IOException {/ / create a closed HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault (); / / create a HttpGet request object HttpGet httpget = new HttpGet (url) / / execute the request, which is equivalent to clicking the send button on postman, and then assigning a value to the HttpResponse object to receive CloseableHttpResponse httpResponse = httpclient.execute (httpget); / / getting the Http response status code, for example, comparing int responseStatusCode = httpResponse.getStatusLine () .getStatusCode () with 200404500 System.out.println ("response status code-- >" + responseStatusCode); / / store the response content in the string object String responseString = EntityUtils.toString (httpResponse.getEntity (), "UTF-8") / / create a Json object and serialize the above string into a Json object JSONObject responseJson = JSON.parseObject (responseString); System.out.println ("respon json from API-- >" + responseJson) / / get the response header information, and return an array of Header [] headerArray = httpResponse.getAllHeaders (); / / create a hashmap object. Through postman, you can see that the request response header information is in the form of Key and value, so we think of HashMap HashMap hm = response () / / enhance the for loop to traverse the headerArray array, adding elements to the hashmap collection for (Header header: headerArray) {hm.put (header.getName (), header.getValue ());} / / print hashmap System.out.println ("response headers->" + hm) }}
The above get method code is quite messy, and you need to read the comments carefully, otherwise the hierarchy is not clear. This code will definitely need to be refactored later. We just started, so just write the test first. At present, the project structure diagram is as follows
2.3 TestNG use case testing Get method
Create a new package under src/test/java: com.qa.tests, then create a new GetApiTest.java class, and write a test case for TestNG to test the Get request method we wrote above.
Package com.qa.tests; import java.io.IOException; import org.apache.http.client.ClientProtocolException;import org.testng.annotations.BeforeClass;import org.testng.annotations.Test; import com.qa.base.TestBase;import com.qa.restclient.RestClient; public class GetApiTest extends TestBase {TestBase testBase; String host; String url; RestClient restClient @ BeforeClass public void setUp () {testBase = new TestBase (); host = prop.getProperty ("HOST"); url = host + "/ api/users";} @ Test public void getAPITest () throws ClientProtocolException, IOException {restClient = new RestClient () RestClient.get (url);}}
Select run as testng and run, and the output result is as follows:
[RemoteTestNG] detected TestNG version 6.14.3response status code-> 200respon json from API-- > {"per_page": 3, "total": 12, "data": [{"last_name": "Bluth", "id": 1, "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg","first_name":"George"},{"last_name":"Weaver","id":2," "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg","first_name":"Janet"},{"last_name":"Wong","id":3,"avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg","first_name":"Emma"}],"page":1,"total_pages":4}response headers-- > {Transfer-Encoding=chunked, Server=cloudflare, CF-RAY=41e822894b39336d-HKG Access-Control-Allow-Origin=*, ETag=W/ "1bb-D+c3sZ5g5u/nmLPQRl1uVo2heAo", Connection=keep-alive, Set-Cookie=__cfduid=d9d93dc43c046707f916670ef491f4c8e1526917157 Expires=Tue, 21-May-19 15:39:17 GMT; path=/; domain=.reqres.in; HttpOnly, Date=Mon, 21 May 2018 15:39:17 GMT, Content-Type=application/json; charset=utf-8, X-Powered-By=Express, Expect-CT=max-age=604800, report-uri= "https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"}PASSED: getAPITest"
Next, we copy the json content of the body of the response content to an online Josn formatted display site (https://www.json.cn/) and see the effect as follows.
This result is the same as on postman, and the data are all right. This is the end of this article on the process of implementing Get requests in Java code based on Httpclient open source libraries.
Thank you for reading this article carefully. I hope the article "Get request method and sample Analysis of Java Interface Automation Test Framework Design" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you 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.