模拟requests.get的行为,来进行单元测试

使用情景:

函数get_and_print内部使用requests.get去请求http://abc.com,响应结果为json,并对json进行操作.
现要测试此函数,因此需要模拟实现requests.get,以保证函数单元测试通过,流程如下:
需要用到测试相关的库为 responses

pip install responses
  1. 配置环境,参考使用pycharm进行单元测试并统计代码覆盖率

  2. 待测试函数代码位于 req.py,代码如下


import responses

def get_and_print():
    res = requests.get('http://www.abc.com').json()
    print('Do something with res:',res)
    return res
  1. 测试代码位于test文件夹的任意python文件中,代码如下
import pytest
import responses

from func.req import get_and_print

# 此处mock指定url的响应
@pytest.fixture
def mocked_responses():
    with responses.RequestsMock() as rsps:
        rsps.add(responses.GET, 'http://www.abc.com', status=200, body='{"id":123}',
                 content_type='application/json')
        yield rsps

# 测试代码需要注入mocked_responses
def test_get_and_print(mocked_responses):
    assert 'id' in get_and_print()

  1. 运行测试,参考步骤1中的链接
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章