JMeter 是一個不錯的負載和性能測試工具,我們也用來做 HTTP API 接口測試。我們的 API 返回結果為 JSON 數據格式。JSON 簡介,JSON 教程。
JSON 已經成為數據交換格式的事實標準:
1. Ajax 調用時的返回數據;
2. 在移動應用中,HTTP 調用時的返回數據;
3. REST Web Service 交換格式;
4. MongoDB 等 NO-SQL 數據庫的數據存儲格式;
5. ...
一定要安裝 Json Path 插件?
- JSON 數據結構簡單的情況
在JSON 數據結構簡單的情況下,使用原生內置的 Regular Expression Extractor(正則表達式)后置處理器來提取數據是可以自如應對的,不一定非要安裝 Json Path 相關插件; - 使用正則表達式的一個優勢在于 JMeter 安裝時就內置了,不用額外安裝;
- 創建和閱讀正則表達式并不容易,隨著 JSON 數據結構復雜度上升,正則表達式是難以理解的,其可維護性自然大打折扣;
安裝 Json Path 相關的插件就是一個較好的解決 JSON 數據結構復雜度的方法。
了解 Json Path 語法
對于熟悉 XPath 語法的人來說(XML 數值提取語法),使用 Json Path 解析 JSON 格式的響應數據比較方便;不過,即使你不熟悉 XPath 也沒關系,來,馬上了解 Json Path 語法就可以了。
了解 jmeter-plugins.org
This project is an independent set of plugins for Apache JMeter, the popular Open-Source load and performance testing tool.
為 JMeter 定制插件,提供獨立的插件集。完整的插件集列表 有六大類:
1. Standard Set
2. Extras Set
3. Extras with Libs Set
4. WebDriver Set
5. XMPP Set
6. Hadoop Set
本次我們要安裝的 Json Path 就包含在 Extras with Libs Set 里面。
注:從官網看似乎推薦使用 JMeter Plugins Manager(目前 0.11 版),Old-Style Releases 頁面里面是原有風格的下載包;
安裝 Extras With Libs Set
Installation and Usage
Just copy the JAR file into JMeter's lib/ext directory.
Then you can start JMeter and add additional items to your Test Plan.
Java version 1.6 and JMeter 2.4 are required.
Extras With Libs Set 這個插件集,目前最新 JMeterPlugins-ExtrasLibs-1.4.0.zip。
- JMeterPlugins-ExtrasLibs-1.4.0.zip 包
│ LICENSE
│ README
│
└─lib
│ asm-5.0.3.jar
│ commons-beanutils-1.8.3.jar
│ commons-lang-2.6.jar
│ commons-pool-1.6.jar
│ ezmorph-1.0.6.jar
│ jedis-2.2.1.jar
│ json-lib-2.4-jdk15.jar
│ json-path-2.1.0.jar
│ json-smart-2.2.jar
│ qpid-client-0.20.jar
│ qpid-common-0.20.jar
│ spring-core-2.5.6.jar
│ spring-jms-2.5.6.jar
│ xom-1.2.10.jar
│
└─ext
JMeterPlugins-ExtrasLibs.jar
- JMeter 基本目錄
├─bin
├─docs
├─extras
├─lib
│ ├─ext
│ └─junit
├─licenses
└─printable_docs
- 將 Extras with Libs Set 解壓到 JMeter 對應目錄即可;
- 重啟 JMeter;
目前在使用中還沒發現什么問題。
使用 Json Path Assertion 檢查返回值是否符合預期
使用 Post Processor:JSON Path Extractor 抽取變量值,供后續使用
- 從 JSON response 中提取數據(每個 Extractor 只能抽取一個變量);
- 存放到 passcode 變量中為后續使用;
- 如果沒有找到,則變量 passcode 中會包含 “NO DEFAULT VALUE”(Default Value);
- 我們可以使用 ${passcode} 在后續元件中注入數據;
對照:使用 Regular Expression Extractor 一次提取多個數據
在一個請求下加一個 Regular Expression Extractor;
-
進行配置:
Reference Name: myVar
Regular Expression: {"succ":"(.+?)","passcode":"(.+?)"}
Template: $1$$2$
1)提取兩個變量,使用 ${myVar_g1} 和 ${myVar_g2} 訪問,加個 Debug Sampler 可以在 View Results Tree 查看;
2)即使使用 Regular Expression Extractor,也建議每個 Extractor 只提取一個變量值,直觀有語義;
Regular Expression Extractor 的配置 -
通過 View Results Tree 查看 Debug Sampler 的結果
通過 View Results Tree 查看 Debug Sampler 的結果 -
通過 View Results Tree listener 內置的 Regex Tester 對正則表達式進行即時測試
通過 [View Results Tree] listener 內置的 Regex Tester 對正則表達式進行即時測試
使用 Listener:Assertion Results 以觀察 Assertion 結果
備注
- jmeter-plugins.org 插件集下載;
- Jayway JsonPath Syntax in GitHub
- goessner: JSONPath expressions
- Parsing JSON responses with JMeter
- JSON path extractor for multiple values