如何模拟'__init__'方法调用的方法

问题描述 投票:1回答:2

我的班级就像

import a

class Demo(object):
    def __init__(self):
        ......
        fun_return_value = a.methodB()
        ......

   def methodA(self):
       ......

测试类就像下面一样

class TestDemo(test.TestCase):

    def setUp(self):
        super(TestDemo, self).setUp()

    def test_methodA(self):
         ......

当我想做方法A的单元测试时,有一个问题,我必须嘲笑a.methodB。但我该怎么做?我检查了文档,什么也没找到。问问其他人并使用@mock.patch("a.methodB")作为TestDemo类的负责人。就像

    @mock.patch("a.methodB")
    class TestDemo(test.TestCase):

        def setUp(self, mock_methodB):
            super(TestDemo, self).setUp()
            mock_methodB.return_value=None

        def test_methodA(self):
             ......

但它没有用。如何模拟“init”方法调用的方法?

python unit-testing mocking init
2个回答
1
投票

找到了解决问题的方法。

class TestDemo(test.TestCase):
    def setUp(self):
        super(TestDemo, self).setUp()
        self.mocks = [mock.patch('a.methodB',
                                  mock.MagicMock(return_value=None))]
        for single_mock in self.mocks:
            single_mock.start()
            self.addCleanup(single_mock.stop)


0
投票

Patch可以用作TestCase类装饰器。它通过装饰类中的每个测试方法来工作。当您的测试方法共享一个公共的补丁集时,这会减少样板代码。 patch()通过查找以patch.TEST_PREFIX开头的方法名来查找测试。默认情况下,这是'测试'

来自the docs。这就是你的代码无效的原因。你可以做的是使用start and stop methods

© www.soinside.com 2019 - 2024. All rights reserved.