简体   繁体   中英

Mocking a method inside class in python test

I am new to Python and writing a unit test for the already existing code.

I have the following Python code structure:

root_project:
-- src 
   -- signUp 
      -- __init__.py 
      -- abc.py 
      -- xyz.py

abc.py contains the following code:

from . import xyz
class Abc: 

      def __init__(self):
         pass 
      
      def start_process(self):
         xyz.start_timer()

I want to mock xyz.start_timer() inside method start_process of class Abc so that start_timer() mock version can be used.

How can I achieve this?

You just need to patch xyz.start_timer() , I just added return to start_process to show that the patching really does what it should:

import xyz
import unittest
from unittest import mock


class Abc:
    def __init__(self):
        pass

    def start_process(self):
        return xyz.start_timer()


class Test_Abc(unittest.TestCase):
    @mock.patch('xyz.start_timer', return_value=True)
    def test_start_process(self, start_process):
        a = Abc()
        self.assertTrue(a.start_process())


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

Out:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

You can simply patch the start_timer function using mock.patch() .

abc.py

import xyz

class Abc: 

      def __init__(self):
         pass 
      
      def start_process(self):
         xyz.start_timer()

test_abc.py

from unittest import mock, TestCase

from abc import Abc

class Test_Abc(TestCase):

    @mock.patch("abc.start_timer")
    def test_start_process(self, mock_start_timer):
        # your test code

Notice that I have patched abc.start_timer and not xyz.start_timer .

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