What is a mock?
Mock testing is to simulate real object behavior in a controlled way. Programmers usually create simulated objects to test the behavior of objects themselves, much like car designers use crash test dummies to simulate the dynamic behavior of people in vehicle crashes
Why use Mock?
The reason why mock testing is used is that real scenarios are difficult to implement or short-term implementation is difficult. The main scenarios are:
-
The real object may not exist yet (the interface has not yet been developed)
-
Real objects are difficult to build (third-party payment joint debugging)
-
Behavior of real objects is hard to trigger (e.g. network errors)
-
Real objects are slow (e.g. a full database, which may need to be initialized before testing)
-
Real objects may contain information and methods that cannot be used for testing (rather than for real work)
-
The real object is the user interface, or includes user pages
-
The real object uses the callback mechanism
-
The behavior of real objects is non-deterministic (such as the current time or the current temperature)
How to use Mock?
Create fake output (results) through code
Interface automation test client Mock
Use the code to simulate the fake interface to return data (the process of accessing the real interface can be omitted)
Take a chestnut: to test the request interface visit interface, in fact, the development work has not been completed yet, we first write the test case, the data is prepared to be empty, and then it can be run through, and after the interface is developed, the corresponding content such as info The data in, the actual results, etc. are modified to run
The visit method is under the APICase class in the base.py module
import unittest
from common.base import APICase
class TestRequest(unittest.TestCase, APICase):
def test_request(self):
"""
1.准备接口接口访问的数据
2.调用接口访问visit方法
3.断言
"""
info = {"headers": "", "json": "", "expected": ""}
# actual = self.visit(info)
actual = ""
self.assertEqual(info['expected'], actual)
mock is a third-party library of python, so you need to install it before using mockpip install mock
Modify the code as follows:
import unittest
from common.base import APICase
from mock import Mock
class TestRequest(unittest.TestCase, APICase):
def test_request(self):
"""
1.准备接口接口访问的数据
2.调用接口访问visit方法
3.断言
"""
info = {"headers": "", "json": "", "expected": ""}
self.visit = Mock(return_value="")
actual = self.visit(info)
# actual = ""
self.assertEqual(info['expected'], actual)
operation result:
When the interface is not developed, write this line of code directly, because the content returned by the mock is called
actual = self.visit(info)
When the interface development is complete, just comment out this line of code
self.visit = Mock(return_value="")
If you want to set the returned data, it is also possible, as follows
Take the previous test registration interface as an example, modify the code as follows:
import unittest
import requests
from mock import Mock
class TestRegister(unittest.TestCase):
def test_register_01(self):
'''步骤:
1.准备测试数据
2.发送接口请求,得到实际结果
3.预期结果和实际结果的断言
'''
# 1.准备测试数据
url = 'http://api.lemonban.com:8766/futureloan/member/register'
method = 'post'
headers = {'X-Lemonban-Media-Type': 'lemonban.v2'}
json_data = {"mobile_phone": "", "pwd": "12345678"}
expected = {
"code": 1,
"msg": "手机号为空",
"data": None,
"copyright": "Copyright 柠檬班 © 2017-2020 湖南省零檬信息技术有限公司 All Rights Reserved"
}
# 2.发送接口请求,得到实际结果
# 因为执行了Mock,所以就不会执行请求真实的接口了
requests.request = Mock(return_value=expected)
response = requests.request(method=method, url=url, headers=headers, json=json_data)
# mock返回的是expected的内容,因此是dict,所以实际结果要把之前代码上的.json去掉
actual = response
# 3.预期结果和实际结果的断言
self.assertEqual(expected, actual)
You only need to modify two codes to access the fake interface
Add the following line of code
requests.request = Mock(return_value=expected)
Modify the following line of code
actual = response.json()
change into actual = response
Service Mock (Mock Server)
method one:
The developed interface is on the server, the real server
I just pretend to be a developer, write a fake server, and write a fake interface, which can be realized through the mockoon tool
Go directly to the official website to download and install
Open mockoon, set the request method, URL, and return content, and click the service button
At this time, you can request the service interface
Method Two:
Test the development technology and make a real service by yourself. It can indeed support more responses, and many steps will be omitted.
Write a service interface in code
from flask import Flask
app = Flask("py44")
@app.route('/member/register', methods=['post'])
def register():
return {"code": 11, "msg": "success"}
app.run(debug=True)
operation result:
The service is only started when the code is run
At this time, you can request the service interface
The flexibility of method 2 is that it can support more responses, such as setting the request body
from flask import Flask, request
app = Flask("py44")
@app.route('/member/register', methods=['post'])
def register():
username = request.form.get('username')
password = request.form.get('password')
if username == 'momo' and password == '123456':
return {"code": 11, "msg": "success"}
return {"code": 22, "msg": "failed"}
app.run(debug=True)
After starting the service, use postman to request
END meager strength
Finally, I would like to thank everyone who has read my article carefully. Looking at the fans’ growth and attention all the way, there is always a need for reciprocity. Although it is not a very valuable thing, you can take it away if you need it:
These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey, and I hope it can help you too!
加入我的软件测试交流群:110685036免费获取~(同行大佬一起学术交流,每晚都有大佬直播分享技术知识点)
Software testing interview applet
The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!
The following interview question sections are covered:
1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux
6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics
method of obtaining: