小编Daw*_*ski的帖子

如何将参数从 mock.patch 传递给 new_callable?

我有代码和测试文件:

代码.py

class Code:

    def do_something_inside(self, a, b, c):
        return a-b-c

    def do_something(self, b, c):
        self.do_something_inside(30, b, c)
Run Code Online (Sandbox Code Playgroud)

测试文件

import unittest
import unittest.mock as mock
from code import Code

class TestStringMethods(unittest.TestCase):
    def setUp(self):
        self.code = Code()

    def do_something_inside_stub(self, a, b, c):
        return a+b+c

    @mock.patch('code.Code.do_something_inside', new_callable=do_something_inside_stub)
    def test_add(self):
        self.assertEquals(self.code.do_something(10, 5), 45)

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

我想使用 do_something_inside_stub 模拟 do_something_inside 方法,但执行失败:

E
======================================================================
ERROR: test_add (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/mock.py", line 1171, in patched
    arg = patching.__enter__() …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-mock python-unittest python-3.6

9
推荐指数
1
解决办法
4695
查看次数