Reference: https://www.jianshu.com/p/15594044ab27
install mock PIP
PIP install pytest -mock (equivalent to mock an upgraded version)
For example:
# File named: mock_demo.py Import Requests DEF mock_request (url): "" " need to be requested mock the " "" return requests.get (url) .status_code DEF invoke_mock_request (url): return mock_request (url)
Test Case
import mock from pytest_mock import mocker from common.mock_demo import invoke_mock_request def test_mock_1(mocker): """方法一:使用的是pytest-mock 中的mocker""" mocker.patch("common.mock_demo.mock_request", return_value=300) assert invoke_mock_request("https://www.baidu.com/") == 300 def test_mock_2(): """方法二:使用的 mock 中patch方法""" with mock.patch("common.mock_demo.mock_request", Return_value = 300 ) AS foo: the Assert invoke_mock_request ( " https://www.baidu.com/ " ) == foo.return_value @ mock.patch ( " common.mock_demo.mock_request " , return_value = 300 ) DEF test_mock_3 (mock_request ): "" " method three: decorator method used mock object function return value to be replaced " "" Assert invoke_mock_request ( " https://www.baidu.com/ " ) == mock_request.return_value
That is: before calling invoke_mock_request () to return to their interfaces dependent mock_request value () method can be replaced, and how this is the case regardless of the method of the return value of the change, we just need to focus on the mock