Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock an external function within a method in a class

I need some help on mock.

I have following code in mymodule.py:

from someModule import external_function

class Class1(SomeBaseClass):
    def method1(self, arg1, arg2):
        external_function(param)

Now I have test code:

import mock
from django.test import TestCase

from mymodule import class1
class Class1Test(TestCase) 
    def test_method1:
        '''how can I mock external_function here?'''
like image 708
user2916464 Avatar asked Nov 14 '13 21:11

user2916464


People also ask

How do you mock a class function?

In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). Since calls to jest. mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables.

How do you mock a function outside the class in Python?

Call MyClass. methodB() where you can pass a MagicMock as request and check if the return value is an instance of http_exception.

How do you mock a method?

Mockito when() method It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute. Following code snippet shows how to use when() method: when(mock.

How do you mock the method of the same class?

Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.


1 Answers

You would write:

class Class1Test(TestCase):

    @mock.patch('mymodule.external_function')
    def test_method1(self, mock_external_function):
        pass

Looking at mymodule the function external_function is directly imported. Hence you need to mock mymodule.external_function as that's the function that will be called when method1 is executed.

like image 155
Simeon Visser Avatar answered Oct 04 '22 16:10

Simeon Visser