Python Mock:如何根据属性测试特定的程序分支

时间:2018-10-25 11:55:45

标签: python-3.x mocking

我想在依赖于公共属性的方法中声明特定分支的结果。这是一个简单的示例:

~$ cat example/branch.py
class Branch:

    flag = 0

    def get(self):
        if self.flag == 0:
            return("Do this")
        else:
            return("Do that")


branch = Branch()
branch.flag = 1
print(branch.get())

~$ python3 example/branch.py
Do that

现在在测试用例中,我模拟了整个类,并尝试使用1预置 flag 。测试用例是这样的:

$ cat example/branchTest.py
from unittest import TestCase, mock
import example

class mockBranchTestCase(TestCase):

    @mock.patch('example.branch.Branch')
    def test_branch(self, mock_Branch):
        mock_Branch.return_value.flag = 1
        inst_branch = example.branch.Branch
        result = inst_branch.get()
        self.assertEqual(result, "Do that")

但是它给了我结果:

[..]
  File "/home/ingo/devel/example/branchTest.py", line 11, in test_branch
    self.assertEqual(result, "Do that")
AssertionError: <MagicMock name='Branch.get()' id='140298461640408'> != 'Do that'

我似乎还不懂嘲笑。如何断言result等于"Do that"

0 个答案:

没有答案