模拟类属性

时间:2019-12-05 20:13:49

标签: python-3.x python-unittest

假设我有一些课程:

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属性,则会收到错误消息。

1 个答案:

答案 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