来自另一个类的Python Mock类实例变量

时间:2019-12-11 03:03:57

标签: python unit-testing mocking pytest python-unittest

我想为foo_method编写单元测试用例。为此编写单元测试的最佳方法是什么?如何模拟Bar对象?

code1.py

from code2 import Bar

class Foo:
    bar_instance = Bar(init1='nothing',init2='nothing')

    @classmethod
    def foo_method(cls):
        Foo.bar_instance.bar_method()

code2.py

class Bar:
   def __init__(self,init1,init2):
      self.init1 = init1
      self.init2 = init2
   def bar_method(self):
       # do something
       pass;

test_code1.py

def test_foo_method_shouldCallBarInstanceBarMethod():

#### how to write this unit test ####

1 个答案:

答案 0 :(得分:1)

您可以使用patch.object模拟bar_method类的Bar

例如

code1.py

from code2 import Bar


class Foo:
    bar_instance = Bar(init1='nothing', init2='nothing')

    @classmethod
    def foo_method(cls):
        Foo.bar_instance.bar_method()

code2.py

class Bar:
    def __init__(self, init1, init2):
        self.init1 = init1
        self.init2 = init2

    def bar_method(self):
        # do something
        pass

test_code1.py

import unittest
from unittest.mock import patch
from code1 import Foo
from code2 import Bar


class TestFoo(unittest.TestCase):
    @patch.object(Bar, 'bar_method', return_value='bar')
    def test_foo_method_shouldCallBarInstanceBarMethod(self, mock_bar_method):
        Foo.foo_method()
        mock_bar_method.assert_called_once()


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

带有覆盖率报告的单元测试结果:

(venv) ☁  python-codelab [master] ⚡  coverage run /Users/ldu020/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/59278328/test_code1.py                                                             
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
(venv) ☁  python-codelab [master] ⚡  coverage report -m                                                                                             
Name                                       Stmts   Miss  Cover   Missing
------------------------------------------------------------------------
src/stackoverflow/59278328/code1.py            5      0   100%
src/stackoverflow/59278328/code2.py            6      1    83%   8
src/stackoverflow/59278328/test_code1.py      10      0   100%
------------------------------------------------------------------------
TOTAL                                         21      1    95%

源代码:https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/59278328