mock server搭建及接口测试简单实例

一、搭建mock server

mock工具很多,这里我们选择用简单易操作的moco服务器

使用前必须先安装java,去相关网站下载Standalone Moco Runner

二、使用mock server

从最简单的hello world开始,使用json做为交互数据使用,编辑config.json为如下文件:

[
{
"request" :
{
"uri" : "/hello"
},
"response" :
{
"text" : "World!"
}
}
]

启动mock server

java -jar moco-runner-0.10.0-standalone.jar  http -p 12888 -c config.json

三:验证

使用httpRequest相关发送get /hello,就会返回world

四:丰富接口后使用unittest、requests写的接口用例如下,包括了get、post、put和deletet接口,代码如下,有需要的可以参考:

import unittest
import requests
import json class TestInterFace(unittest.TestCase): def setUp(self): #print "xxxx"
self.domain='http://localhost:12888'
self.json_headers={"content-type":'application/json'}
print "before each test" def tearDown(self):
print "End One Testcase" def test_get_all_posts(self):
print "test get all posts"
result=requests.get(self.url_test("/posts")).json()
self.assertEqual(len(result),3)
print len(result)
self.assertEqual(result[0]['title'],'first post')
#print 'xxx'
self.assertEqual(result[0]['url'],'/posts/1') self.assertEqual(result[-1]['title'],'how to learn interface test')
self.assertEqual(result[-1]['url'],'/posts/3') def test_get_first_post(self):
print "test get first post"
result=requests.get(self.url_test("/posts/1")).json()
self.assertEqual(len(result),2)
self.assertEqual(result['title'],'first post')
self.assertEqual(result['content'],'this is my first post') def url_test(self,path):
return self.domain + path def test_create_post(self):
#headers={"content-type":'application/json'}
json_data=json.dumps({"title": "new post","content": "new post"})
result=requests.post(self.url_test('/posts'),data=json_data,headers=self.json_headers)
print result.status_code
print result.text
self.assertEqual(result.status_code,200)
self.assertEqual(result['sucess'],'true') def test_modify_post(self):
headers={"content-type":'application/json'}
json_data=json.dumps({"title": "new post","content": "new post"})
result=requests.put(self.url_test('/posts/1'),data=json_data,headers=self.json_headers)
print result.status_code
print result.text
self.assertEqual(result.status_code,200)
#self.assertTrue def test_delete_post(self):
headers={"content-type":'application/json'}
json_data=json.dumps({"title": "new post","content": "new post"})
result=requests.delete(self.url_test('/posts/2'))
print result.status_code
print result.text
self.assertEqual(result.status_code,200)
#self.assertTrue if __name__=='__main__':
unittest.main()
上一篇:E-trunk和Eth-trunk 区别


下一篇:Mock Server的搭建