Search code examples
pythonpython-3.xpython-mock

Is there anyway to print a statement when Python mock function called?


I am now trying to mock a function using mock.patch, for eg:

with mock.patch.object(self.myClass, 'MyClassMethod', return_value=None) as mock_MyMethod:
    self.myClass.start()
    mock_MyMethod.assert_called_once_with()

Now I am want to make MyClassMethod to print "hello word!!" when it gets called. Can anyone please help me in finding solution for this.

Thanks in advance,


Solution

  • You could use side_effect. First you define you printing function:

    def hello():
        print("hello world!!!")
        return mock.DEFAULT
    

    and then you initialize your mock object like this:

    with mock.patch.object(..., side_effect=hello)