nGrinder中快速編寫groovy指令碼03-在指令碼中新增引數
阿新 • • 發佈:2018-12-22
一、通過UI介面新增
通過 UI 設定:指令碼 -> 新建指令碼 -> 顯示高階配置
生成程式碼如下:
@RunWith(GrinderRunner)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class TestRunner {
public static GTest test
public static HTTPRequest request
public static NVPair[] headers = []
public static NVPair[] params = []
public static Cookie[ ] cookies = []
@BeforeProcess
public static void beforeProcess() {
HTTPPluginControl.getConnectionDefaults().timeout = 6000
test = new GTest(1, "www.baidu.com")
request = new HTTPRequest()
// =========下面是我剛才新增的引數=========
// Set header datas
List<NVPair> headerList = new ArrayList< NVPair>()
headerList.add(new NVPair("Connection", "keep-alive"))
headerList.add(new NVPair("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0"))
headerList.add(new NVPair("Content-Type", "application/json"))
headers = headerList.toArray()
// Set param datas
List< NVPair> paramList = new ArrayList<NVPair>()
paramList.add(new NVPair("name", "jjing"))
paramList.add(new NVPair("sex", "girl"))
params = paramList.toArray()
// Set cookie datas
List<Cookie> cookieList = new ArrayList<Cookie>()
cookieList.add(new Cookie("mytoken", "xxxxxxxxx", "www.baidu.com", "", new Date(32503647599000L), false))
cookies = cookieList.toArray()
// =========上面是我剛才新增的引數=========
grinder.logger.info("before process.");
}
@BeforeThread
public void beforeThread() {
test.record(this, "test")
grinder.statistics.delayReports=true;
grinder.logger.info("before thread.");
}
@Before
public void before() {
request.setHeaders(headers)
cookies.each { CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
grinder.logger.info("before thread. init headers and cookies");
}
@Test
public void test(){
HTTPResponse result = request.GET("https://www.baidu.com", params)
assertThat(result.statusCode, is(200))
// 這是我通過引導頁手動新增的斷言
assertThat(result.getText(), containsString("jjing"))
}
}
可以看到這種方式是在@beforeProcess中新增引數。
二、直接在指令碼中新增
根據在指令碼中新增的位置不同,可以分為以下幾種方式:
1、在 @BeforeProcess 註解的方法裡新增
這種方法跟第一種方法的效果是一樣的
List<NVPair> paramList = new ArrayList<NVPair>()
paramList.add(new NVPair("accessToken", "xxxxxxxxx"))
// ...可以新增多個
params = paramList.toArray()
2、直接在TestRunner類的靜態變數中新增
在整個類最前面定義靜態變數的地方,直接給變數賦值:
public static NVPair[] params = [
new NVPair("accessToken", "9de6d5f2b62d4bb686de8033fd00bc65")
]
3、在 @Test 註解的方法中新增
在傳送request請求的方法裡新增引數:
// HTTPResponse result = request.GET("https://www.baidu.com", params)
HTTPResponse result = request.GET("https://www.baidu.com", [new NVPair("accessToken", accessToken)] as NVPair[])
到底選擇哪種方式,要根據具體的引數型別和業務場景來決定。