Học API Automation Testing Sở hữu Relaxation Assured

Relaxation Assured là 1 trong những thư viện được dùng nhiều nhất trong API Automation testing. Trong tutorial này mình sẽ chỉ dẫn khách hàng về những khái niệm như là Relaxation API, API Testing, API Automation Testing,…

API là gì?

API là viết tắt của (Utility Programming Interface) – Giao diện lập trình ứng dụng, nó là 1 tập hợp những features mà có thể được truy cập bởi những ứng dụng khác. Do đấy, nó như là 1 giao diện giữa những hệ thống phần mềm khác nhau và thiết lập sự tương tác và trao đổi dữ liệu của chúng.

API Testing là gì?

Trong nền công nghiệp phát triển thành phần mềm tiên tiến, siêu nhiều những ứng dụng / hệ thống được thiết kế dựa trên mô hình 3 lớp (3-tier structure mannequin).

Bố lớp đấy là:

  • Presentation Tier – Tầng tương tác quản lý có người mua, dùng để hiển thị những thành phần giao diện để tương tác có người mua như tiếp nhận thông tin, thông tin lỗi
  • Logic Tier – Tầng logic, tầng này cũng có thể được gọi là enterprise tier, nhiệm vụ của tầng này là đảm nhận và xử lí những enterprise của hệ thống. Tầng này cũng làm cho nhiệm vụ vận động, xử lí thông tin giữa 2 tầng Presentation và Knowledge Tier
  • Knowledge Tier – nơi lưu trữ và trích xuất dữ liệu từ những hệ quản trị CSDL hay những file trong hệ thống. Cho phép tầng Enterprise logic thực hành những truy vấn dữ liệu.

3 layers đề cập trên sẽ giao tiếp có nhau thông qua những dịch vụ (companies) mà từng layer phân phối để tạo nên ứng dụng, lớp này cũng ko cần biết bên trong lớp kia làm cho gì mà chỉ cần biết lớp kia phân phối dịch vụ gì cho mình và dùng nó mà thôi.

Lớp Logic bao gồm toàn bộ những bussiness logic của hệ thống, nó phức tạp hơn toàn bộ những lớp còn lại, do đấy việc thực hành kiểm thử trên lớp này là siêu cần thiết. Việc kiểm thử trên lớp bussiness logic này được gọi là API Testing.

Đối có UI Testing, chúng ta check dựa trên những hành vi của người mua như nhập data qua bàn phím, thực hành click on 1 button nào đấy trên display,… thì đối có API Testing, chúng ta thực hành gửi những request và verify xem output từ API trả về cho chúng ta xem hệ thống trả về có đúng như chúng ta mong muốn hay ko. Dữ liệu mà API trả về cho chúng ta có thể là JSON có RESTful API hoặc là XML có SOAP.

Để hiểu thêm về REST và SOAP thì khách hàng có thể tham khảo bài viết Chọn net service phải chăng nhất

REST Assured là gì

Relaxation-assured (RestA) là 1 thư viện Java DSL được xây dựng trên nền HTTP Builder (thư viện tạo HTTP request), cho phép thực hành gửi request và đánh giá response. Nói đơn giản là 1 thư viện được xây dựng sẵn để việc thực hành kiểm thử API trở nên dễ dàng hơn. Thực tế, có siêu nhiều thư viện mà chúng ta có thể dùng, nhưng kinh nghiệm cho thấy, Relaxation Assured dễ dùng hơn hết, nhiều chức năng hơn, và đặc biệt là nó có 1 cùng đồng tương trợ siêu lớn.

REST API testing có REST Assured

Lý thuyết nhiều rồi, chúng ta sẽ thực hành thực hành api testing qua thí dụ thực tế sau 😀

Dự án A được đảm nhận xây dựng 1 hệ thống kiếm tìm video cho khách hàng JP, bên cạnh việc xây dựng 1 web site kiếm tìm thì khách hàng còn mong muốn public API của hệ thống ra bên cạnh. Vậy là tester trong dự án lại buộc phải đảm nhận vai trò check những api endpoint mà hệ thống sẽ public.

Đề bài đặt ra cho tester như sau:

  • Check case 1: Search video có từ khoá cho trước, giới hạn số video trả về là 4 movies.
    • Từ khoá: API Testing
    • Parameter:
      • {tukhoa}: Từ khoá của video mong muốn search
      • {soluongvideo}: Số lượng video mong muốn trả về, trong check case mong muốn là 4
    • URL Endpoint: sentayho.com.vn/search/{tukhoa}/movies.json?num_of_videos={soluongvideo}
    • Kết quả mong muốn: Trả về kết quả dưới dạng JSON, trong đấy có hyperlink dẫn tới những movies, tiêu đề và mô tả của những video đấy
    • Điều kiện để check case cross:
      • Trong kết quả trả về buộc phải có HTTP Standing Code
      • Kết quả trả về buộc phải chứa từ khoá kiếm tìm
      • Chỉ có cao nhất} 4 movies được trả về
      • Những video trả về ko trùng lặp nhau
  • Check case 2: Search video có id của video, nhưng lần này sẽ trả về thông tin chi tiết của video đấy và những video liên quan tới video đấy (kiểu như suggestion video trên youtube vậy), cũng giới hạn số lượng những video liên quan trả về là 4
    • Parameter:
      • { video_id }: Từ khoá của video mong muốn search
      • {soluongvideo}: Số lượng video mong muốn trả về, trong check case mong muốn là 4
    • URL Endpoint: sentayho.com.vn/video/listing/information.json?video_ids={video_id}&num_related_return={soluongvideo}
    • Kết quả mong muốn: Trả về kết quả dưới dạng JSON, trong đấy có thông tin chi tiết về video đấy và những video liên quan
    • Điều kiện để check case cross:
      • Trong kết quả trả về buộc phải có HTTP Standing Code
      • Kết quả trả về buộc phải liên quan tới video được kiếm tìm
      • Chỉ có cao nhất} 4 movies được trả về
      • Những video liên quan được trả về ko trùng lặp nhau
Xem Thêm  Mắt Cười: Khai phá bí hiểm Tướng số, Vận mệnh Sang, Hèn

Vậy, giải pháp của anh tester là gì? Hãy cùng mình sang phần tiếp theo nhé

REST API testing có REST Assured – (cont.)

Để giải quyết bài toán đưa ra trên trên, tester buộc phải xây dựng 1 framework và tích hợp Relaxation Assured làm cho thư viện để testing API. Framework tester xây dựng cũng buộc phải đáp ứng tiêu chí Re-usability để có thể check cho những api endpoint khác mà ko buộc phải mất công viết lại code.

Ngay bây giờ} chúng ta khởi đầu !!

1. Xây dựng Venture construction.

Trước tiên, chúng ta sẽ khởi tạo 1 Maven challenge, và setup những thư phần như bên dưới:

  • Utils folder sẽ chứa 2 class là HelperMethods và RestUtil
    • HelperMethods: Class này sẽ gồm những helpers có thể reusalbe
    • RestUtil: class này sẽ bao gồm những strategies liên quan tới thư viện Relaxation Assured
  • Trong thư phần ApiTests sẽ có 2 class là Example1Test và Example2Test, đây là 2 courses chứa những check instances và những assertions
  • Trong thư phần TestSuite sẽ có class AllApiTest, đây là class Check Runner của chúng ta, class này sẽ đảm nhận việc run toàn bộ những check instances

2. Cài đặt những dependencies

  • Chúng ta sẽ add chiếc dependencies sau vào sentayho.com.vn.
    • Junit Library: Chiếc này là check framework
    • Hamcrest library: thư viện dành cho những technique assertion
    • Jayway Relaxation Assured: Đây là Relaxation assured, thư viện mà chúng ta nhắc tới nãy giờ trong bài viết 😀
  • Cấu trúc file sentayho.com.vn của chúng ta sẽ như bên dưới: <?xml model=”1.0″encoding=”UTF-8″?> <challenge xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 sentayho.com.vn/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.5min.apitest</groupId> <artifactId>5min-apitest</artifactId> <model>1.0-SNAPSHOT</model> <!-Dependencies-> <dependencies> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <model>1.3</model> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-junit</artifactId> <model>2.0.0.0</model> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <model>4.12</model> </dependency> <dependency> <groupId>com.jayway.restassured</groupId> <artifactId>json-schema-validator</artifactId> <model>2.8.0</model> </dependency> <dependency> <groupId>com.jayway.restassured</groupId> <artifactId>rest-assured</artifactId> <model>2.8.0</model> </dependency> </dependencies> <!-Profiles-> <profiles> <profile> <id>AllApiTests</id> <activation> <activeByDefault>true</activeByDefault> </activation> <construct> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <model>2.19.1</model> <configuration> <contains> <embody>**/AllApiTest.class</embody> </contains> </configuration> </plugin> </plugins> </pluginManagement> </construct> </profile> </profiles> </challenge>

3. Sau khoản thời gian add xong những dependencies thì chúng ta sẽ bắt tay vào code

  • RestUtil.java

    Đây là class giúp chúng ta viết những frequent strategies để giúp chúng ta tiện dùng sau này

    package deal Utils; import sentayho.com.vnAssured; import sentayho.com.vnentType; import sentayho.com.vnPath; import sentayho.com.vnonse; import static sentayho.com.vnAssured.*; public class RestUtil { //World Setup Variables public static String path; //Relaxation request path /* ***Units Base URI*** Earlier than beginning the check, we should always set the sentayho.com.vnURI */ public static void setBaseURI (String baseURI){ sentayho.com.vnURI = baseURI; } /* ***Units base path*** Earlier than beginning the check, we should always set the sentayho.com.vnPath */ public static void setBasePath(String basePathTerm){ sentayho.com.vnPath = basePathTerm; } /* ***Reset Base URI (after check)*** After the check, we should always reset the sentayho.com.vnURI */ public static void resetBaseURI (){ sentayho.com.vnURI = null; } /* ***Reset base path (after check)*** After the check, we should always reset the sentayho.com.vnPath */ public static void resetBasePath(){ sentayho.com.vnPath = null; } /* ***Units ContentType*** We should always set content material kind as JSON or XML earlier than beginning the check */ public static void setContentType (ContentType Kind){ given().contentType(Kind); } /* ***search question path of first instance*** It’s equal lớn “barack obama/movies.json?num_of_videos=4” */ public static void createSearchQueryPath(String searchTerm, String jsonPathTerm, String param, String paramValue) { path = searchTerm + “/” + jsonPathTerm + “?” + param + “=” + paramValue; } /* ***Returns response*** We ship “path” as a parameter lớn the Relaxation Assured’a “get” technique and “get” technique returns response of API */ public static Response getResponse() { //System.out.print(“path: ” + path +”n”); return get(path); } /* ***Returns JsonPath object*** * First convert the API’s response lớn String kind with “asString()” technique. * Then, ship this String formatted json response lớn the JsonPath class and return the JsonPath */ public static JsonPath getJsonPath (Response res) { String json = sentayho.com.vnring(); //System.out.print(“returned json: ” + json +”n”); return new JsonPath(json); } }

  • HelperMethods.java

    Đây cũng là 1 class chứa những frequent features để chúng ta có thể dùng lại trong 2 courses Example1Test và Example2Test

    package deal Utils; import sentayho.com.vnPath; import sentayho.com.vnonse; import sentayho.com.vn.*; import static sentayho.com.vnrtEquals; public class HelperMethods { /* Confirm the http response standing returned. Verify Standing Code is 200? We are able to use Relaxation Assured library’s response’s getStatusCode technique */ public static void checkStatusIs200 (Response res) { assertEquals(“Standing Verify Failed!”, 200, sentayho.com.vntatusCode()); } /* Get Video Ids (For instance 1) We are able to use get technique of Relaxation Assured library’s JsonPath Class’s get technique A part of a response is proven beneath: “objects”: [{ “id”: 519377522, …. We can get all id’s with this code -> “jp.get(“items.id”);” this will return all id’s under “items” tag. */ public static ArrayList getVideoIdList (JsonPath jp) { ArrayList videoIdList = jp.get(“items.id”); return videoIdList; } /* Get Related Video Ids (For example 2) Structure of response is shown below: items: “related”: [{ “id”: 519148754, …. In order to get all id’s under related tag, We can use JsonPath’s get method like “jp.get(“items.related.id”);” It will give us all id’s under related tag. */ public static ArrayList getRelatedVideoIdList (JsonPath jp) { //jp.get method returns all ids ArrayList relatedVideoList = jp.get(“items.related.id”); /* Result of relatedVideosList: [[519148754, 519115214, 519235328, 519235341]] I’ve lớn convert above end result on this format: [519148754, 519115214, 519235328, 519235341] So as lớn break up first component of “relatedVideosList” and assign it lớn a brand new ArrayList (as splittedRelatedVideoList) I did beneath operation. */ ArrayList splittedRelatedVideoList = (ArrayList) sentayho.com.vn(0); return splittedRelatedVideoList; } //Merge videoIdList and relatedVideoIdList as mergedVideoList public static ArrayList mergeLists (ArrayList videoList, ArrayList relatedVideoList){ ArrayList mergedVideoList = new ArrayList(videoList); sentayho.com.vnll(relatedVideoList); return mergedVideoList; } //Discover Duplicate Movies public static boolean findDuplicateVideos (Record<Integer> videoIdList) { for (int i=0; i< sentayho.com.vn(); i++) { if(Collections.frequency(videoIdList, sentayho.com.vn(i)) > 1){ sentayho.com.vntln(“This video id is duplicated: ” + sentayho.com.vn(i)); return false; } } return true; } }​

  • sentayho.com.vn – sentayho.com.vn
Xem Thêm  Graphite là gì? Ứng dụng quan yếu của Graphite vào đời sống

Đây là 2 class quan yếu nhất, courses này chứa những assertions để kiểm thử những kết quả trả về từ api

  • Example1Test.java

    package deal ApiTests; import Utils.*; import sentayho.com.vnentType; import sentayho.com.vnPath; import sentayho.com.vnonse; import sentayho.com.vnt.*; import sentayho.com.vnodSorters; import static sentayho.com.vnrtTrue; @FixMethodOrder(MethodSorters.NAME_ASCENDING) //For Ascending order check execution public class Example1Test { //First, I declared Response and JsonPath objects. non-public Response res = null; //Response object non-public JsonPath jp = null; //JsonPath object /* Second, we should always do setup operations, get JSON response from the API and put it into JsonPath object Then we’ll do question and manipulations with JsonPath class’s strategies. We are able to do all the preparation operations after @Earlier than Junit annotation. */ @Earlier than public void setup (){ //Check Setup sentayho.com.vnaseURI(“http://api.5min.com”); //Setup Base URI sentayho.com.vnasePath(“search”); //Setup Base Path sentayho.com.vnontentType(ContentType.JSON); //Setup Content material Kind sentayho.com.vnteSearchQueryPath(“barack obama”, “movies.json”, “num_of_videos”, “4”); //Assemble the trail res = sentayho.com.vnesponse(); //Get response jp = sentayho.com.vnsonPath(res); //Get JsonPath } @Check public void T01_StatusCodeTest() { //Confirm the http response standing returned. Verify Standing Code is 200? sentayho.com.vnkStatusIs200(res); } @Check public void T02_SearchTermTest() { //Confirm the response contained the related search time period (barack obama) sentayho.com.vnrtEquals(“Title is incorrect!”, (“Search outcomes for “barack obama””), jp.get(“api-info.title”)); //assertThat(jp.get(“api-info.title”), containsString(“barrack obama”)); } @Check public void T03_verifyOnlyFourVideosReturned() { //Confirm that solely 4 video entries have been returned sentayho.com.vnrtEquals(“Video Measurement shouldn’t be equal lớn 4”, 4, sentayho.com.vnideoIdList(jp).measurement()); } @Check public void T04_duplicateVideoVerification() { //Confirm that there isn’t any duplicate video assertTrue(“Duplicate movies exist!”, sentayho.com.vnDuplicateVideos(HelperMethods.getVideoIdList(jp))); } @Check public void T05_printAttributes() { //Print video title, pubDate & length printTitlePubDateDuration(jp); } @After public void afterTest (){ //Reset Values sentayho.com.vntBaseURI(); sentayho.com.vntBasePath(); } //******************* //***Native Strategies*** //******************* //Prints Attributes non-public void printTitlePubDateDuration (JsonPath jp) { for(int i=0; i < sentayho.com.vnideoIdList(jp).measurement(); i++ ) { sentayho.com.vntln(“Title: ” + jp.get(“objects.title[” + i + “]”)); sentayho.com.vntln(“pubDate: ” + jp.get(“objects.pubDate[” + i + “]”)); sentayho.com.vntln(“length: ” + jp.get(“objects.length[” + i + “]”)); sentayho.com.vnt(“n”); } } }

  • sentayho.com.vn package deal ApiTests; import Utils.*; import sentayho.com.vnentType; import sentayho.com.vnPath; import sentayho.com.vnonse; import sentayho.com.vnt.*; import sentayho.com.vnodSorters; import sentayho.com.vnyList; import static sentayho.com.vnrtEquals; import static sentayho.com.vnrtTrue; @FixMethodOrder(MethodSorters.NAME_ASCENDING) //For Ascending order check execution public class Example2Test { non-public Response res = null; //Response non-public JsonPath jp = null; //JsonPath /* We should always do setup operations, get JSON response from the API and put it into JsonPath object Then we’ll do question and manipulations with JsonPath class’s strategies. We are able to do all the preparation operations after @Earlier than Junit annotation. */ @Earlier than public void setup (){ //Check Setup sentayho.com.vnaseURI(“http://api.5min.com”); //Setup Base URI sentayho.com.vnasePath(“video”); //Setup Base Path //On this instance, I assigned full path manually in beneath code line. sentayho.com.vn = “listing/information.json?video_ids=519218045&num_related_return=4”; sentayho.com.vnontentType(ContentType.JSON); //Setup Content material Kind res = sentayho.com.vnesponse(); //Get response jp = sentayho.com.vnsonPath(res); //Set JsonPath } @Check public void T01_StatusCodeTest() { //Confirm the http response standing returned. Verify Standing Code is 200? sentayho.com.vnkStatusIs200(res); } @Check public void T02_SearchTermTest() { //Confirm the response contained the related search time period (519218045) assertEquals(“Id doesn’t match!”, “519218045”, sentayho.com.vnideoIdList(jp).get(0).toString()); } @Check public void T03_verifyExtraFourVideosReturned() { //Confirm that additional 4 video entries have been returned as associated movies assertEquals(“Associated video Measurement shouldn’t be equal lớn 4”, 4, sentayho.com.vnelatedVideoIdList(jp).measurement()); } @Check public void T04_duplicateVideoVerification() { //Verify duplicate movies exist? assertTrue(“Duplicate movies exist!”, sentayho.com.vnDuplicateVideos(getMergedVideoLists())); } @Check public void T05_printAttributes() { //Print attributes printAttributes(jp); } @After public void afterTest (){ //Reset Values sentayho.com.vntBaseURI(); sentayho.com.vntBasePath(); } //******************* //***Native Strategies*** //******************* //Returns Merged Video Lists (Video Record + Associated Video Record) non-public ArrayList getMergedVideoLists (){ return sentayho.com.vneLists(HelperMethods.getVideoIdList(jp), sentayho.com.vnelatedVideoIdList(jp)); } //Prints Attributes non-public void printAttributes(JsonPath jp) { for(int i=0; i <getMergedVideoLists().measurement(); i++ ) { //Prints Video Record Attributes if(jp.get(“objects.title[” + i + “]”) != null) { sentayho.com.vntln(“title: ” + jp.get(“objects.title[” + i + “]”)); sentayho.com.vntln(“Tablets: ” + jp.get(“objects.permittedDeviceTypes.Tablets[” + i + “]”)); sentayho.com.vntln(“Handsets: ” + jp.get(“objects.permittedDeviceTypes.Handsets[” + i + “]”)); sentayho.com.vntln(“ConnectedDevices: ” + jp.get(“objects.permittedDeviceTypes.ConnectedDevices[” + i + “]”)); sentayho.com.vntln(“Computer systems: ” + jp.get(“objects.permittedDeviceTypes.Computer systems[” + i + “]”)); sentayho.com.vntln(“Length: ” + jp.get(“objects.length[” + i + “]”)); sentayho.com.vnt(“n”); //Verify that despatched video has associated movies? If sure print their attributes if (jp.get(“objects.associated.title[” + i + “][” + i + “]”) != null) { for (int j = 0; j < sentayho.com.vnelatedVideoIdList(jp).measurement(); j++) { sentayho.com.vntln(“title: ” + jp.get(“objects.associated.title[0][” + j + “]”)); sentayho.com.vntln(“Tablets: ” + jp.get(“objects.associated.permittedDeviceTypes.Tablets[0][” + j + “]”)); sentayho.com.vntln(“Handsets: ” + jp.get(“objects.associated.permittedDeviceTypes.Handsets[0][” + j + “]”)); sentayho.com.vntln(“ConnectedDevices: ” + jp.get(“objects.associated.permittedDeviceTypes.ConnectedDevices[0][” + j + “]”)); sentayho.com.vntln(“Computer systems: ” + jp.get(“objects.associated.permittedDeviceTypes.Computer systems[0][” + j + “]”)); sentayho.com.vntln(“Length: ” + jp.get(“objects.associated.length[0][” + j + “]”)); sentayho.com.vnt(“n”); } } } } } }
Xem Thêm  Mcafee Livesafe Là Gì – Mcafee Livesafe (Free 1 5)

AllApiTest.java

  • Class này được xem như là 1 check suite, đảm nhận việc run toàn bộ những check instances đã được outlined trên 2 class Example1Test và Example2Test package deal TestSuite; import sentayho.com.vnith; import sentayho.com.vne; import sentayho.com.vnase1Test; import sentayho.com.vnase2Test; @RunWith(Suite.class) @Suite.SuiteClasses({ sentayho.com.vns, sentayho.com.vns, }) public class AllApiTest { }

4. Execute Check Circumstances

Sau khoản thời gian đã code xong, việc cuối cùng chúng ta cần làm cho là thực hành chạy những check instances, và chúng ta có thể làm cho việc này bằng 2 bí quyết

– Bí quyết 1: Dùng command line

Tại trong file sentayho.com.vn mà mình đã đề cập trên trên, trên node <profiles> mình đã outline sentayho.com.vn làm cho primary check suite. Do vậy lúc run bằng command line thì java sẽ run file này trước tiên

1. Bật CMD 2. cd vào root listing của supply code 3. Run command sau: mvn check -PallApiTests

  • Bí quyết 2: Run từ IntelliJ hoặc Eclipse

Lời kết

Vậy là trong tutorial này, mình đã chỉ dẫn khách hàng làm cho như thế nào để có thể thực hành kiểm thử những api endpoint. Hy vọng là bài viết này sẽ giúp khách hàng có chiếc nhìn tổng quan về api testing và có thể vận dụng được trong những dự án thực tế mà khách hàng đang làm cho.

Khách hàng có thể tham khảo supply code của mình tại đây

Tham khảo: sentayho.com.vn