我对此很陌生我已经写了下面的代码进行测试
def test_monthly_schedule(self):
with patch('employee.requests.get') as mocked_get:
mocked_get.return_value.ok = True
mocked_get.return_value.text = "Success"
schedule=self.e1.monthly_schedule()
mocked_get.assert_called_with("http://www.google.com")
self.assertEqual(schedule,"success")
这是为了
def monthly_schedule(self):
response=requests.get(f"http://www.google.com")
if response.ok:
return response.text
else:
return "Bad response"
发现错误
raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: get('http://www.google.com')
Not called
请注意代码缩进。 patch上下文管理器应该可以正常工作。
例如
employee.py
:
import requests
class Employee():
def monthly_schedule(self):
response = requests.get("http://www.google.com")
if response.ok:
return response.text
else:
return "Bad response"
test_employee.py
:
import unittest
from employee import Employee
from unittest.mock import patch
class TestEmployee(unittest.TestCase):
def setUp(self):
self.e1 = Employee()
def test_monthly_schedule(self):
with patch('employee.requests.get') as mocked_get:
mocked_get.return_value.ok = True
mocked_get.return_value.text = "Success"
schedule = self.e1.monthly_schedule()
mocked_get.assert_called_with("http://www.google.com")
self.assertEqual(schedule, "Success")
if __name__ == '__main__':
unittest.main()
带有覆盖率报告的单元测试结果:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Name Stmts Miss Cover Missing
---------------------------------------------------------------------------
src/stackoverflow/60680124/employee.py 7 1 86% 10
src/stackoverflow/60680124/test_employee.py 15 0 100%
---------------------------------------------------------------------------
TOTAL 22 1 95%
Python版本:Python 3.7.5