这是以下的单元测试解决方案Python 3.7.5
:
file1.py
:
class SomeHelper():
def __init__(self):
self.my_var = 0
file2.py
:
import file1
class MyClass():
@classmethod
def calculate(cls):
x = 1
inst = file1.SomeHelper()
if x > inst.my_var:
return True
return False
test_file2.py
:
import unittest
from unittest.mock import patch
from file2 import MyClass
class TestMyClass(unittest.TestCase):
@patch('file2.file1')
def test_calculate(self, mock_file1):
inst = mock_file1.SomeHelper.return_value
inst.my_var = 0.5
to_test = MyClass.calculate()
self.assertTrue(to_test)
mock_file1.SomeHelper.assert_called_once()
@patch('file2.file1')
def test_calculate_2(self, mock_file1):
inst = mock_file1.SomeHelper.return_value
inst.my_var = 2
to_test = MyClass.calculate()
self.assertFalse(to_test)
mock_file1.SomeHelper.assert_called_once()
if __name__ == '__main__':
unittest.main()
带有覆盖率报告的单元测试结果:
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
Name Stmts Miss Cover Missing
------------------------------------------------------------------------
src/stackoverflow/50242955/file1.py 3 1 67% 3
src/stackoverflow/50242955/file2.py 8 0 100%
src/stackoverflow/50242955/test_file2.py 16 0 100%
------------------------------------------------------------------------
TOTAL 27 1 96%
源代码:https ://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/50242955