https://cloud.tencent.com/developer/article/1737211?from=article.detail.1465591
前言
前段時間介紹了Mock基本知識以及市面上常見的Mock工具(Mock工具介紹),今天重點介紹小編在測試過程中使用的Mock工具-Moco。
爲什麼使用Moco
1.Mock簡便性:簡單上手,儘量減少學習成本。
2.項目開源(https://github.com/dreamhead/moco)
3.部署容易:Moco的運行非常簡單,只需要一行命令即可。
4.Mock參數配置:Moco可以將需要返回的具體結果寫在Json文件中;YApi可以通過mockjs、json-schema進行數據Mock,擴展性更好,但指定返回結果成本較高。
Moco介紹
Moco本身支持API和獨立運行兩種方式。通過使用API,開發人員可以在JUnit、JBehave等測試測試框架裏使用Moco,極大程度地降低了集成點測試的複雜度。
Moco可以提供以下服務:
- HTTP APIs
- Socket APIs
- REST API
Moco原理簡介
Moco會根據一些配置,啓動一個真正的HTTP服務(會監聽本地的某個端口)。當發起請求滿足一個條件時,它就給回覆一個應答。Moco的底層沒有依賴於像Servlet這樣的重型框架,而是基於一個叫Netty網絡應用框架直接編寫的,這樣一來,繞過了複雜的應用服務器,所以,它的速度是極快的。
Moco獨立運行所需環境
Moco獨立運行時所需準備的有:
- Java運行環境
- moco-runner-0.11.0-standalone.jar
如何運行Moco
Moco的運行非常簡單,只需要一行命令即可
如在命令行中運行:
java -jar <path-to-moco-runner> http -p <monitor-port> -c < configuration -file>
<path-to-moco-runner>:moco-runner-0.11.0-standalone.jar包的路徑
<monitor-port>:http服務監聽的端口
<configuration -file>:配置文件路徑
Moco工作流程
Moco配置文件詳解
1.配置文件添加註釋
[
{
"description": "這是一個註釋行,對該接口進行描述",
"request":{
"uri": "/sogou"
},
"response": {
"file": "sogou.response"
}
}
]
2.約定接口Uri
可以在uri中使用正則表達式進行匹配
其中request這個key爲請求相關內容,response爲返回的相關內容
[
{
"description": "request中uri必須是/sogou,才能匹配該接口",
"request":{
"uri": "/sogou"
},
"response": {
"file": "sogou.response"
}
}
]
3.約定請求參數
[
{
"description": "request中必須包含參數param=test,才能匹配該接口",
"request":{
"queries":{
"param": "test"
}
},
"response": {
"file": "sogou.response"
}
}
]
4.約定請求方法
[
{
"description": "request必須是get請求,才能匹配此接口,除此外還支持post|put|delete|Head方法",
"request":{
"method": "get",
},
"response": {
"file": "sogou.response"
}
}
]
5.約定HTTP版本
[
{
"description": "request必須是HTTP/1.0,才能匹配此接口",
"request":{
"version": "HTTP/1.0",
},
"response": {
"file": "sogou.response"
}
}
]
6.約定HTTP請求頭部
[
{
"description": "request必須包含頭部:application/json,才能匹配此接口",
"request":{
"method": "get",
"headers": {
"content-type": "application/json"
}
},
"response": {
"file": "sogou.response"
}
}
]
7.約定Cookie
[
{
"description": "request必須包含cookies:login-true,才能匹配此接口",
"request":{
"method": "get",
"cookies": {
"login": "true"
}
},
"response": {
"file": "sogou.response"
}
}
]
8.約定請求Form
[
{
"description": "request必須包含表單:name-sogou,才能匹配此接口",
"request":{
"method": "get",
"forms": {
"name": "sogou"
}
},
"response": {
"file": "sogou.response"
}
}
]
9.設置Response Content
[
{
"description": "接口匹配後,response返回文件sogou.response,文件編碼爲GBK",
"request":{
"method": "get"
},
"response": {
"file": "sogou.response",
"charset": "GBK"
}
}
]
10.設置Response 狀態碼
[
{
"description": "接口匹配後,response返回狀態碼500",
"request":{
"method": "get"
},
"response": {
"status": "500"
}
}
]
11.設置重定向
[
{
"description": "接口匹配後,返回重定向地址",
"request":{
"uri": "/sogou"
},
"redirectTo": "www.sogou.com"
}
]
Moco不足
Moco的使用很簡單,配置也很方便,目前更是提供了http、rest、socket服務。但是也僅僅是能stub出接口,模擬出簡單的場景。如果接收到請求後需要做一些處理,如需查詢數據庫、進行運算、或者一些複雜的操作,就無能爲力了。所以是否選用Moco,就取決於開發者是否只是需要一個簡單的模擬服務器。