Python unittest模拟类和类方法

时间:2019-07-15 17:29:00

标签: python python-3.x unit-testing mocking python-unittest

我觉得这可能相对简单,但我正在拔头发以使它正常工作。我想模拟整个类,然后为此类方法之一指定返回值。

我已经看着here,还有其他几个问题,当然还有docs。我仍然无法使它正常工作。请在下面查看我的简单示例。

目录tmp的内容:

tmp
├── __init__.py
├── my_module.py
└── test_my_module.py

my_module.py的内容:

class MyClass:
    def __init__(self):
        # Do expensive operations that will be mocked in testing.
        self.a = 7

    def my_method(self):
        # For sake of simple example, always return 1.
        return 1


def create_class_call_method():
    """Create MyClass instance and call its my_method method, returning
    the result."""
    instance = MyClass()
    value = instance.my_method()
    return value

test_my_module.py的内容:

import unittest
from unittest.mock import patch, Mock

from tmp import my_module


class MyClassTestCase(unittest.TestCase):

    def test_create_class_call_method(self):
        # Attempt to patch MyClass as well as specify a return_value for
        # the my_method method (spoiler: this doesn't work)
        with patch('tmp.my_module.MyClass',
                   my_method=Mock(return_value=2)):
            value = my_module.create_class_call_method()

        self.assertEqual(value, 2)


if __name__ == '__main__':
    unittest.main()

运行test_my_module.py的结果:

2 != <MagicMock name='MyClass().my_method()' id='140234477124048'>

Expected :<MagicMock name='MyClass().my_method()' id='140234477124048'>
Actual   :2

我尝试过的其他一些事情:

  • 而不是像..., my_method=Mock(return_value=2))语句中的patch那样,解压缩字典:**{'my_method.return_value': 2}
  • 嵌套的with patch语句。外部语句很简单,例如with patch('tmp.my_module.MyClass'):,内部语句则尝试对my_method进行补丁,例如:with patch('tmp.my_module.MyClass.my_method, return_value=2)
  • 使用补丁装饰器代替上下文管理器
  • 将patch语句更改为with patch('tmp.my_module.MyClass') as p:,然后在with语句内,尝试像这样设置pp.evaluate = Mock(return_value=2)

感谢您的帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

我不确定create_class_call_method的实现,但是请尝试以下操作:

from unittest import mock

class MyClassTestCase(unittest.TestCase):
    @mock.patch('tmp.my_module.MyClass.my_method')
    @mock.patch('tmp.my_module.MyClass.__init__')
    def test_create_class_call_method(self, my_class_init, my_method_mock):
        my_class_init.return_value = None
        my_method.return_value = 2

        value = my_module.create_class_call_method()

        self.assertEqual(value, 2)

答案 1 :(得分:0)

我找到了一个更好的解决方案。简而言之,我们需要模拟return_value模拟中的MyClass。这是有效的测试代码:

import unittest
from unittest.mock import patch, Mock, MagicMock

from tmp import my_module


class MyClassTestCase(unittest.TestCase):

    def test_create_class_call_method(self):
        # Create a mock to return for MyClass.
        m = MagicMock()
        # Patch my_method's return value.
        m.my_method = Mock(return_value=2)

        # Patch MyClass. Here, we could use autospec=True for more
        # complex classes.
        with patch('tmp.my_module.MyClass', return_value=m) as p:
            value = my_module.create_class_call_method()

        # Method should be called once.
        p.assert_called_once()
        # In the original my_method, we would get a return value of 1.
        # However, if we successfully patched it, we'll get a return
        # value of 2.
        self.assertEqual(value, 2)


if __name__ == '__main__':
    unittest.main()

成功的结果:

Ran 1 test in 0.002s

OK