자바 인터페이스 자동화 테스트 프레임 워 크 및 단언 상세 설명
앞의 글 에서 말 했 듯 이 이전에 쓴 Get 방법 은 비교적 번 거 로 웠 다.Get 요청 을 어떻게 하 는 지 뿐만 아니 라 http 응답 상태 코드 와 JSON 변환 을 가 져 오 는 방법 도 썼 다.지금 우 리 는 추출 을 해 야 합 니 다.Get 요청 방법 을 설계 하고 한 가지 일 만 해 야 합 니 다.그것 은 get 요청 을 어떻게 보 내 는 지,다른 것 은 상관 하지 마 세 요.
요청 후 HTTP 응답 대상 을 되 돌려 주 는 것 을 알 고 있 습 니 다.따라서 get 방법의 반환 값 형식 을 응답 대상 으로 바 꾸 고 반환 문 구 를 가 져 와 코드 를 재 구성 한 후 get 방법 코드 는 다음 과 같 습 니 다.
package com.qa.restclient;
import java.io.IOException;
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;
public class RestClient {
 //1. Get     
 public CloseableHttpResponse get(String url) throwsClientProtocolException, IOException {
  //        HttpClient  
  CloseableHttpClienthttpclient = HttpClients.createDefault();
  //    HttpGet     
  HttpGethttpget = newHttpGet(url);
  //    ,   postman       ,     HttpResponse    
  CloseableHttpResponsehttpResponse = httpclient.execute(httpget);
  return httpResponse;
 }
}
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;
   public int RESPNSE_STATUS_CODE_200 = 200;
   public int RESPNSE_STATUS_CODE_201 = 201;
   public int RESPNSE_STATUS_CODE_404 = 404;
   public int RESPNSE_STATUS_CODE_500 = 500;
   //       
   public TestBase() {
     try{
       prop= new Properties();
       FileInputStreamfis = 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();
     }
   }
}
package com.qa.tests;
import java.io.IOException;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.methods.CloseableHttpResponse;
import org.testng.Assert;
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;
   CloseableHttpResponse closeableHttpResponse;
   @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();
     closeableHttpResponse= restClient.get(url);
     //        200
     int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
     Assert.assertEquals(statusCode,RESPNSE_STATUS_CODE_200, "response status code is not 200");
   }
}2.JSON 해석 도구 클래스 쓰기
위 부분 에 서 는 Get 요청 과 상태 코드 가 200 인지 에 대한 단언 만 적 었 습 니 다.그 다음 에 우 리 는 JSON 해석 도구 류 를 써 서 제 이 슨 의 내용 에 대한 단언 을 편리 하 게 해 야 한다.
다음은 JSON 데이터 캡 처.
 
 위 는 표준적 인 제 이 슨 의 응답 내용 캡 처,첫 번 째 붉 은 동그라미'perpage"는 json 대상 입 니 다."per "에 따라페이지 에서 대응 하 는 값 을 찾 으 려 면 3 이 고 두 번 째 빨 간 동그라미 인'data'는 대상 이 아 닌 JSON 배열 입 니 다.안에 있 는 값 을 직접 받 을 수 없고 배열 을 옮 겨 다 녀 야 합 니 다.
다음은 JSON 이 분석 한 도구 방법 류 를 쓰 겠 습 니 다.첫 번 째 빨 간 동그라미 의 JSON 대상 이 라면 해당 하 는 값 을 되 돌려 줍 니 다.data 배열 에 있 는 json 대상 의 값 을 분석 해 야 한다 면 구조 방법 은 배열 의 첫 번 째 요소 의 내용 을 기본 으로 해석 합 니 다.
src/main/java 에 가방 을 새로 만 듭 니 다:com.qa.util,그리고 새 가방 에 TestUtil.java 클래스 를 만 듭 니 다.
package com.qa.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestUtil {
 /**
 *
 * @param responseJson ,              json   json  
 * @param jpath,  jpath         json         
 * jpath    :1) per_page 2)data[1]/first_name ,data   json  ,[1]    
 * /first_name   data          json      first_name
 * @return,  first_name  json        
 */
 //1 json    
 public static String getValueByJPath(JSONObject responseJson, String jpath){
  Objectobj = responseJson;
  for(String s : jpath.split("/")) {
  if(!s.isEmpty()) {
   if(!(s.contains("[") || s.contains("]"))) {
    obj = ((JSONObject) obj).get(s);
   }else if(s.contains("[") || s.contains("]")) {
    obj =((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("\\[")[1].replaceAll("]", "")));
   }
  }
  }
  return obj.toString();
 }
}3.TestNG 테스트 용례
다음은 저희 TestNG 테스트 용례 코드 는 다음 과 같 습 니 다.
package com.qa.tests;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qa.base.TestBase;
import com.qa.restclient.RestClient;
import com.qa.util.TestUtil;
public class GetApiTest extends TestBase{
	TestBase testBase;
	String host;
	String url;
	RestClient restClient;
	CloseableHttpResponse closeableHttpResponse;
	@BeforeClass
	public void setUp() {
		testBase = new TestBase();
		host = prop.getProperty("HOST");
		url = host + "/api/users?page=2";
	}
	@Test
	public void getAPITest() throws ClientProtocolException, IOException {
		restClient = new RestClient();
		closeableHttpResponse = restClient.get(url);
		//        200
		int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
		Assert.assertEquals(statusCode, RESPNSE_STATUS_CODE_200, "response status code is not 200");
		//              
  String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(),"UTF-8"); 
  //  Json  ,          Json   
  JSONObject responseJson = JSON.parseObject(responseString); 
  //System.out.println("respon json from API-->" + responseJson); 
  //json    
  String s = TestUtil.getValueByJPath(responseJson,"data[0]/first_name");
  System.out.println(s);
	}	
}
[RemoteTestNG] detected TestNGversion 6.14.3
Eve
PASSED: getAPITest
String s = TestUtil.getValueByJPath(responseJson,"data[1]/id");
String s = TestUtil.getValueByJPath(responseJson,"per_page");여기 서 TestNG 의 단언 방법 을 간단히 말씀 드 리 겠 습 니 다.우 리 는 일반적으로 단언 코드 를 써 야 합 니 다.그렇지 않 으 면 이러한 단원 테스트 코드 는 의미 가 없습니다.다음은 status Code 와 json 에서 해석 한 first단언
package com.qa.tests;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qa.base.TestBase;
import com.qa.restclient.RestClient;
import com.qa.util.TestUtil;
public class GetApiTest extends TestBase{
	TestBase testBase;
	String host;
	String url;
	RestClient restClient;
	CloseableHttpResponse closeableHttpResponse;
	@BeforeClass
	public void setUp() {
		testBase = new TestBase();
		host = prop.getProperty("HOST");
		url = host + "/api/users?page=2";
	}
	@Test
	public void getAPITest() throws ClientProtocolException, IOException {
		restClient = new RestClient();
		closeableHttpResponse = restClient.get(url);
		//        200
		int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
		Assert.assertEquals(statusCode, RESPNSE_STATUS_CODE_200, "response status code is not 200");
		//              
  String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(),"UTF-8"); 
  //  Json  ,          Json   
  JSONObject responseJson = JSON.parseObject(responseString); 
  //System.out.println("respon json from API-->" + responseJson); 
  //json    
  String s = TestUtil.getValueByJPath(responseJson,"data[0]/first_name");
  System.out.println(s);
  Assert.assertEquals(s, "Eve","first name is not Eve");
	}
}
Assert.assertEquals(“    ”, "    ","            ");이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.