使用嘲笑模拟函数内部的变量

时间:2020-10-10 12:50:58

标签: python unit-testing mocking python-unittest

我在模拟测试方面遇到问题:

<nav>
  <ul>
    <li><a class="active" href="index.html">Home</a></li>
    <li><a href="boyshome.html">Boys Campus</a></li>
    <li><a href="girlshome.html">Girls Campus</a></li>
    <li><a href="calculator.html">GPA Calculator</a></li>
  </ul>
</nav>

现在,如果我想测试功能test(),我需要模拟var_test,所以我正在做的是:

from module import FUNC
class A():
  def __init__(self):
    self.var = FUNC()

  def test(self):
    var_test = self.var.get()
    return var_test

请有人能告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

您尝试修补的目标可能不正确。对于下面的示例,我们应该在 get 中修补 FUNC 类的 a.py 方法。所以补丁目标应该是a.FUNC.get

例如

a.py

from module import FUNC


class A():
    def __init__(self):
        self.var = FUNC()

    def test(self):
        var_test = self.var.get()
        return var_test

module.py

class FUNC(object):
    def get(self):
        pass

test_a.py

import unittest
from unittest import mock
from a import A


class TestA(unittest.TestCase):
    def test_test(self):
        with mock.patch('a.FUNC.get') as mo:
            mo.return_value = "no"
            a = A()
            self.assertEqual("no", a.test())


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

测试结果:

 ⚡  coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/64293629/test_a.py && coverage report -m --include='./src/**'
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name                                   Stmts   Miss  Cover   Missing
--------------------------------------------------------------------
src/stackoverflow/64293629/a.py            7      0   100%
src/stackoverflow/64293629/module.py       3      1    67%   3
src/stackoverflow/64293629/test_a.py      11      0   100%
--------------------------------------------------------------------
TOTAL                                     21      1    95%