接口測試——Java + TestNG 國家氣象局接口(json解析)實例


后端測試,主要以測試接口為主。需要代碼支撐,近期便找了個天氣接口搗鼓了。

使用到的工具是:Eclipse + TestNG + Maven + ReportNG,全國城市編碼:http://www.cnblogs.com/oucbl/p/6138963.html,接口地址:http://www.weather.com.cn/data/cityinfo/城市編碼.html

先看一下代碼架構,如下所示:

建的是maven工程,個人覺得這樣下載依賴包較方便。工程科分為四部分:功能代碼,測試case,報表文件和配置文件。網絡上也有很多這樣的實例,我只是列舉些我在做的過程中所遇到的問題吧,也當一個記錄。maven不會配置,可參見我之前寫的隨筆。

功能代碼

Common

 1 package com.CityWether.CityInfo;
 2 
 3 import net.sf.json.JSONException;
 4 import net.sf.json.JSONObject;
 5 
 6 public class Common {
 7     public static String getJsonValue(String JsonString, String JsonId) {
 8         String JsonValue = "";
 9         //trim()去掉字符串首尾的空格
10         if (JsonString == null || JsonString.trim().length() < 1) {
11             return null;
12         }
13         try {
14             JSONObject obj1 = new JSONObject(JsonString);
15             JsonValue = obj1.getString(JsonId);
16         } catch (JSONException e) {
17             e.printStackTrace();
18         }
19         return JsonValue;
20     }
21 }
View Code

URLConnection

 1 package com.CityWether.CityInfo;
 2 
 3 import java.net.HttpURLConnection;
 4 import java.net.URL;
 5 
 6 public class URLConnection {
 7     public static HttpURLConnection getConnection(String url){
 8         HttpURLConnection connection = null;
 9         try {
10             // 打開和URL之間的連接
11             URL postUrl = new URL(url);
12             connection = (HttpURLConnection) postUrl.openConnection();
13              // 設置通用的請求屬性
14             connection.setDoOutput(true);
15             connection.setDoInput(true);
16             connection.setRequestMethod("GET");
17             connection.setUseCaches(false);
18             connection.setInstanceFollowRedirects(true);
19             connection.setRequestProperty("Content-Type", "application/json");
20             connection.setRequestProperty("Charset", "utf-8");
21             connection.setRequestProperty("Accept-Charset", "utf-8");
22         } catch (Exception e) {
23             e.printStackTrace();
24         } 
25         return connection;
26     }
27 }
View Code

CityWeather

 1 package com.CityWether.CityInfo;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.DataOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.net.HttpURLConnection;
 8 
 9 public class CityWeather {
10     private String url="";
11     
12     public String geturl() {
13         return url;
14     }
15     
16     public static String formatString(String s) {  
17         if (s != null) {  
18               s = s.replaceAll("\ufeff", "");  
19         }  
20         return s;  
21     }
22     
23     public String getHttpRespone(String cityCode) throws IOException {
24         String line = "";
25         String httpResults = "";
26         url=("http://www.weather.com.cn/data/cityinfo/" + cityCode + ".html");
27         try {
28             HttpURLConnection connection = URLConnection.getConnection(url);
29             // 建立實際的連接
30             connection.connect();
31             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
32             while ((line = reader.readLine()) != null) {
33                 httpResults = httpResults + line.toString();
34             }
35             reader.close();
36             // 斷開連接
37             connection.disconnect();
38         } catch (Exception e) {
39             e.printStackTrace();
40         }
41         return httpResults;
42     }
43 }
View Code

測試case

 1 package com.CityWether.CityInfo;
 2 
 3 import java.io.IOException;
 4 
 5 import org.testng.Assert;
 6 import org.testng.Reporter;
 7 import org.testng.annotations.Test;
 8 
 9 import com.CityWether.CityInfo.CityWeather;
10 import com.CityWether.CityInfo.Common;
11 
12 public class TestCase {
13     public String httpResult= null, weatherinfo= null, city=null,expect_city = null;
14     public static String cityCode="";
15     CityWeather weather=new CityWeather();
16     
17     @Test(priority=0)
18     public void getHuaihua() throws IOException{
19         expect_city="懷化";
20         cityCode="101251201";
21         resultCheck(cityCode, expect_city);
22     }
23     
24     @Test(priority=1)
25     public void getHuitong() throws IOException{
26         expect_city="會同";
27         cityCode="101251206";
28         resultCheck(cityCode, expect_city);
29     }
30     
31     @Test(priority=2)
32     public void getChangsha() throws IOException{
33         expect_city="長沙";
34         cityCode="101250101";
35         resultCheck(cityCode, expect_city);
36     }
37     
38     @Test(priority=3)
39     public void getBaoshan() throws IOException{
40         expect_city="寶山";
41         cityCode="101020300";
42         resultCheck(cityCode, expect_city);
43     }
44     
45     @Test(priority=4)
46     public void getShanghai() throws IOException{
47         expect_city="上海";
48         cityCode="101020100";
49         resultCheck(cityCode, expect_city);
50     }
51     
52     @Test(priority=5)
53     public void Minhang() throws IOException{
54         expect_city="閔行";
55         cityCode="101020200";
56         resultCheck(cityCode, expect_city);
57     }
58     
59     public void resultCheck(String cityCode, String expect_city) throws IOException{
60         System.setProperty("org.uncommons.reportng.escape-output", "false");
61         Reporter.log("【正常用例】:獲取"+expect_city+"天氣成功!");
62         httpResult=weather.getHttpRespone(cityCode);
63         Reporter.log("<p><span style=\"color:#FF0000\">請求地址: "+weather.geturl()+"</span></p>");
64         Reporter.log("【返回結果】: "+httpResult);
65         weatherinfo=Common.getJsonValue(httpResult, "weatherinfo");
66         city=Common.getJsonValue(weatherinfo, "city");
67         Reporter.log("<p>【用例結果】: resultCode=>expected: " + expect_city + " ,actual: "+ city+"</p>");
68         Assert.assertEquals(city,expect_city);  
69         Reporter.log("<p></p>");
70         Reporter.log("<p>"+"------------------------------------------------------------------------------"+"</p>");
71     }
72 }
View Code

報表文件示例

報表html文件位置在如下所示:

代碼實現如上就完成,需要配置pom.xml文件和testng.xml文件,可參照如下:

pom.xml

pom.xml文件是下載依賴包的,特別方便

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4 
 5   <groupId>com</groupId>
 6   <artifactId>CityWether</artifactId>
 7   <version>0.0.1-SNAPSHOT</version>
 8   <packaging>jar</packaging>
 9 
10   <name>CityWether</name>
11   <url>http://maven.apache.org</url>
12 
13   <properties>
14     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15   </properties>
16 
17   <dependencies>
18     <dependency>
19       <groupId>junit</groupId>
20       <artifactId>junit</artifactId>
21       <version>3.8.1</version>
22       <scope>test</scope>
23     </dependency>
24     <dependency>
25         <groupId>org.json</groupId>
26         <artifactId>json</artifactId>
27         <version>20171018</version>
28     </dependency>
29     <dependency>
30         <groupId>org.testng</groupId>
31            <artifactId>testng</artifactId>
32         <version>6.9.10</version>
33   </dependency>
34   <dependency>
35     <groupId>org.uncommons</groupId>
36     <artifactId>reportng</artifactId>
37     <version>1.1.4</version>
38  </dependency>
39  <dependency>
40     <groupId>com.google.inject</groupId>
41     <artifactId>guice</artifactId>
42     <version>4.0</version>
43  </dependency>
44  <dependency>
45     <groupId>velocity</groupId>
46     <artifactId>velocity-dep</artifactId>
47     <version>1.4</version>
48  </dependency>
49   </dependencies>
50 </project>
View Code

這里需要注意的是,由於接口返回的是json數據,所以必須導入json依賴包:

1 <dependency>
2    <groupId>org.json</groupId>
3    <artifactId>json</artifactId>
4    <version>20171018</version>
5 </dependency>

testng.xml

testng.xml文件是用於運行的,運行程序直接運行該文件即可:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
 3 <suite name="suite1">
 4     <test name="test1">
 5         <classes>
 6             <class name="com.CityWether.CityInfo.TestCase" />
 7         </classes>
 8     </test>
 9     <listeners>
10       <listener class-name="org.uncommons.reportng.HTMLReporter" /> 
11       <listener class-name="org.uncommons.reportng.JUnitXMLReporter" />
12     </listeners>
13 </suite>
View Code

問題總結

自己在完成過程中,過程中遇到如下問題:

1、接口返回的數據是亂碼

如下所示:

經百度科普,是因為BOM報頭報錯,可參見該博文:http://blog.csdn.net/u012519664/article/details/41596857?%3E,里面有詳細介紹。

解決辦法:

在CityWeather類中代碼下加上如下代碼即可:

  public static String formatString(String s) {  
        if (s != null) {  
              s = s.replaceAll("\ufeff", "");  
        }  
        return s;  
    }

2、Common類中導包錯誤

Common類中代碼導入如下包,運行程序報錯

import org.json.JSONException;
import org.json.JSONObject;

報錯為:

解決辦法為:

重新導入JSON包即可,如下:

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

3、注意:測試報告美化是依賴ReportNG包的,切莫忘記


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM