简体   繁体   中英

How to mock the method which was called by the method of '__init__'

My Class just like

import a

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

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

the test class just like below

class TestDemo(test.TestCase):

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

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

When I want to make methodA's unittest, there has the question that I must mock the a.methodB.But how can I do that?I checked the doc,and found nothing. Ask others and use @mock.patch("a.methodB") at the head of the class TestDemo.Just like

    @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):
             ......

But it didn't work.How to mock the method which was called by the method of " init "?

has find the way to fix it.

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)

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. patch() finds tests by looking for method names that start with patch.TEST_PREFIX. By default this is 'test'

From the docs . That's why your code isn't working. What you can do instead is use the start and stop methods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM