Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python@patch decorator中使用self_Python_Unit Testing_Mocking_Patch - Fatal编程技术网

在python@patch decorator中使用self

在python@patch decorator中使用self,python,unit-testing,mocking,patch,Python,Unit Testing,Mocking,Patch,我正在尝试使用python的mock.patch实现带有nose的单元测试 class A: def setUp(self): self.b = 8 #contrived example @patch.object('module.class', 'function', lambda x: self.b) def testOne(self): # do test # 在这里,补丁抱怨它不了解self(这是正确的)。以干净的方式获得此类

我正在尝试使用python的mock.patch实现带有nose的单元测试

class A:

    def setUp(self):
        self.b = 8 #contrived example

    @patch.object('module.class', 'function', lambda x: self.b)
    def testOne(self):
        # do test #
在这里,补丁抱怨它不了解self(这是正确的)。以干净的方式获得此类功能的最佳方式是什么


我知道我可以使用全局变量,或者我可以在测试中模拟它(但这涉及到我在测试结束时清理对象)。

你不能在方法装饰器上使用
self
,因为你在类定义中,而对象不存在。如果您真的想访问<代码>自身>代码>,而不只是使用一些静态值,您可以考虑以下方法:<代码> toTest<代码>是我的Python路径中的一个模块,<代码> fn>代码>是我要修补的方法,而且我使用固定的代码> ReutoLyValue而不是一个更可读的例子

函数。
class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.b = 8 #contrived example

    def testOne(self):
        with patch('totest.fn', return_value=self.b) as m:
            self.assertEqual(self.b, m())
            self.assertTrue(m.called)

    @patch("totest.fn")
    def testTwo(self,m):
        m.return_value = self.b
        self.assertEqual(self.b, m())
        self.assertTrue(m.called)
testOne()。在
testTwo()
(这是我的标准方式)中,我在测试开始时设置了mock
m
,然后使用它


最后,我使用了
patch()
而不是
patch.object()
,因为我不太明白为什么需要
patch.object()
,但您可以随意更改它

测试二看起来不错。没有使用patch.object替代patch的具体原因。我想这是最好的解决办法。谢谢回答得很好,谢谢!