# weateher_r.py class Mock_weather(): def weather(self): '''天氣接口''' pass def weather_result(self): '''模擬天氣接口''' result = self.weather() if result['result'] == '雪': print('下雪了!!!') elif result['result'] == '雨': print('下雨了!!!') elif result['result'] == '晴天': print('晴天!!!!') else: print('返回值錯誤!') return result['status']
# test_01.py import pytest from test_01.weather_r import Mock_weather def test_01(mocker): # 實例化 p = Mock_weather() moke_value = {'result': "雪", 'status': '下雪了!'} # 通過object的方式進行查找需要mock的對象 p.weather = mocker.patch.object(Mock_weather, "weather", return_value=moke_value) result =p.weather_result() assert result=='下雪了!' def test_02(mocker): # 實例化 product = Mock_weather() # Mock的返回值 mock_value = {'result': "雨", 'status': '下雨了!'} # 第一個參數必須是模擬mock對象的完整路徑 product.weather = mocker.patch('test_01.weather_r.Mock_weather.weather',return_value=mock_value) result = product.weather_result() assert result=='下雨了!' if __name__ == '__main__': pytest.main(['-vs'])
上述內容為pytest中的pytest-mock的簡單使用,如果有更好的方法可以下方留言一起探討