Home > Software engineering >  Mocking a method inside class in python test
Mocking a method inside class in python test

Time:08-01

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?

CodePudding user response:

You just need to patchxyz.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

CodePudding user response:

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.

  • Related