一、什么是mock
mock,即模拟。模拟一个对象,模拟接口返回。
二、什么场景要用mock
1、单元测试:
由于单元测试仅针对当前单元进行测试,这就要求所有的内部或者外部依赖都应该是稳定的,采用mock的方法模拟跟本单元依赖的其他单元,可以将测试重点放在当前单元功能,排除外界因素干扰,提升测试精准度。
2、前后端联调
3、第三方接口依赖:
在做接口自动化时,依赖的第三方接口不稳定或者未开发完成时,则可以mock该接口
4、提高测试覆盖率:
部分异常场景,难以模拟时,咱们可以mock接口返回对应错误,来验证不同的情况
三、如何实现
1、flask模块帮助轻松实现mock
什么是flask?
Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。
2、如何做?
(1)、安装flask框架(前提是已经装好python3环境)
pip3 install flask
(2)、检查安装情况,如下图:
pip3 show flask

3、代码实战
(1)、第一个hello world
from flask import Flask,request //导入flask模块
app = Flask(__name__) //实例化flask
@app.route("/") //指定url
def hello_world():
return "hello,world" //返回


运行效果:

通过curl 命令来检查:
curl 'http://127.0.0.1:5000/'

(2)、具体的代码:
from flask import Flask,request
app = Flask(__name__)
@app.route("/")
def hello_world():
return "hello,world"
@app.route("/testGet")
def test_get():
return {"name":"hello"}
@app.route("/testGetParams")
def test_get_params():
return request.args
@app.route("/testPost",methods=["POST"])
def test_post():
return {"city":"shenzhen"}
@app.route("/testPostParams",methods=["POST"])
def test_post_params():
return request.json
@app.route('/testGetPost',methods=['GET','POST'])
def test_get_post():
if request.method == 'GET':
return 'this is get method'
elif request.method == 'POST':
return 'this is post method'
if __name__ == '__main__':
app.run()
(3)、culr 验证:
curl -H 'Content-Type:application/json' -d '{"city":"shenzhen"}' -X POST 'http://127.0.0.1:5000/testPostParams'
返回:{"city":"shenzhen"}
如此一来,通过flask,咱们即可轻松实现一分钟mock一个接口哦。