2015-09-25 64 views
-1

我想提高寫作功能自動化測試我的REST API的需要編寫自動REST API測試的幫助?我該如何改進?

這裏有一個例子:

Q1可有人批評我的測試或者看看是否有改進的空間?

Q2另外我打算在AppTest類中編寫一系列API測試...有沒有一種方法或一個函數或實用工具,可以將響應存儲在文件中或執行一系列API測試?

package com.jaway.restassured.rest_assured; 

import static com.jayway.restassured.RestAssured.get; 

import java.util.List; 

import org.json.JSONException; 
import org.json.JSONArray; 
import org.testng.Assert; 
import org.testng.*; 
import org.testng.annotations.Test; 
import org.testng.annotations.*; 
import org.testng.annotations.DataProvider; 
import org.testng.asserts.SoftAssert; 


import com.jayway.restassured.response.*; 

public class AppTest { 

    String url = "http://restcountries.eu/rest/v1/name/"; 

    @Test(dataProvider = "getData") 
    public void getRequestFindCapital(String country, String expected_capital, String expected_region, String expected_trans_it) throws JSONException{ 

     SoftAssert softAssert = new SoftAssert(); 
     //Make a request to fetch the capital of norway 
     Response resp = get(url + country); 
     System.out.println(url + country); 
     JSONArray jsonResponse =new JSONArray(resp.asString()); 
     System.out.println(resp.asString()); 

     //Declare variables 
     String actual_capital = jsonResponse.getJSONObject(0).getString("capital"); 
     String actual_region = jsonResponse.getJSONObject(0).getString("region"); 
     List<Object> actual_translations = resp.jsonPath().getList("translations.it"); 
     String actual_translations_string = actual_translations.toString().replaceAll("[\\[\\]]", ""); 
     System.out.println(actual_translations); 
     System.out.println(actual_translations_string); 

     softAssert.assertEquals(actual_capital, expected_capital); 
     softAssert.assertEquals(actual_region, expected_region); 
     softAssert.assertEquals(actual_translations_string, expected_trans_it); 
     softAssert.assertAll(); 
    } 

    @DataProvider 
     public Object[][] getData() { 
      return new Object[][]{ 
       {"Norway", "Oslo","Europe", "Norvegia"}, 
       {"Britain", "London","Europe","Regno Unito"}, 
       {"Bangladesh","Dhaka","Asia","Bangladesh"}}; 
     } 

} 

回答

0

我通常在OpenEJB或Arquillian寫我的ITests。使用OpenEJB,測試類可以在啓動測試之前啓動嵌入式容器。您可以在這裏查看示例:http://openejb.apache.org/examples-trunk/index.html。符合JEE6,JEE7尚未發佈...

+0

現在符合JEE7標準 –

0
  1. 你只打算幸福路徑。因此,爲了改進您的測試,您可能需要添加一些錯誤的輸入並確認您將收到適當的錯誤。例如,您可以提供不存在的國家並驗證答案。 通過這種方式,您可以添加一些功能測試。 我建議還要添加一些非功能性測試,例如性能,以便衡量您的REST延遲。
  2. 有幾個實用程序允許保存REST調用和響應。我最喜歡的是PostMan插件(僅在Chrome商店中搜索)。
0

您也可能想要查看Cucumber編寫功能測試的框架,它可以簡化很多編寫測試用例的過程。我個人覺得JUnit或TestNG只適用於需要存根/嘲諷的單元測試。

您可以編寫測試用例用簡單的英語,如:

Feature: Countries API 
    Scenario: Retrieve Capital City 
    Given the specified country is "United States" 
    When I make the API request 
    Then the response should be valid JSON 
    And it should contain property "city" with value "Washington, D.C." 

然後你就可以寫爲實現使用任何黃瓜執行這些英文句子。在這種情況下,我最喜歡的是Node.js,但他們有幾個實現。這種方法的優點是現在你甚至可以讓團隊的非技術成員編寫端到端的測試用例。