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() 

 

转载于:https://www.cnblogs.com/landhu/p/5385746.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值