我正在努力改进我的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 :(得分:0)
答案 1 :(得分: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."
然后你可以使用任何Cucumber实现为这些英语句子编写实现。在这种情况下,我最喜欢的是Node.js,但它们有几个实现。这种方法的优点是,现在您甚至可以让团队的非技术成员编写端到端的测试用例。
答案 2 :(得分:0)
我经常用OpenEJB或Arquillian写我的ITests。使用OpenEJB,测试类可以在启动测试之前启动嵌入式容器。您可以在此处查看示例:http://openejb.apache.org/examples-trunk/index.html。是否符合JEE6,JEE7尚未发布...