假设我有一些课程:
class Worker:
_processor: Processor
def set_processor(self, processor: Processor):
self._processor = processor
def start_work(self, data: bytes):
self._processor.parse(data)
测试set_processor
方法非常简单,像这样:
def test_set_processor():
mock_processor = Mock()
worker = Worker()
worker.set_processor(mock_processor)
assert worker._processor == mock_processor
我们只是将模拟传递给set_processor
方法,然后检查self._processor
是否等于模拟。
但是如何测试start_work
方法?我想确定self._processor
将被data
调用吗?
如果我尝试修补_processor
属性,则会收到错误消息。
答案 0 :(得分:1)
这是单元测试解决方案:
worker.py
:
from typing import Any
Processor = Any
class Worker:
_processor: Processor
def set_processor(self, processor: Processor):
self._processor = processor
def start_work(self, data: bytes):
self._processor.parse(data)
test_worker.py
:
import unittest
from worker import Worker
from unittest.mock import Mock
class TestWorker(unittest.TestCase):
def test_set_processor(self):
mock_processor = Mock()
worker = Worker()
worker.set_processor(mock_processor)
assert worker._processor == mock_processor
worker.start_work(b'')
mock_processor.parse.assert_called_once_with(b'')
if __name__ == '__main__':
unittest.main()
覆盖率100%的单元测试结果:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
(venv) ☁ python-codelab [master] ⚡ coverage report -m
Name Stmts Miss Cover Missing
-------------------------------------------------------------------------
src/stackoverflow/59202648/test_worker.py 13 0 100%
src/stackoverflow/59202648/worker.py 8 0 100%
-------------------------------------------------------------------------
TOTAL 21 0 100%
源代码:https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/59202648