如何在类中的方法中模拟外部函数

时间:2013-11-14 21:51:25

标签: python unit-testing mocking python-mock

我需要一些关于模拟的帮助。

我在mymodule.py中有以下代码:

from someModule import external_function

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

现在我有测试代码:

import mock
from django.test import TestCase

from mymodule import class1
class Class1Test(TestCase) 
    def test_method1:
        '''how can I mock external_function here?'''

1 个答案:

答案 0 :(得分:4)

你会写:

class Class1Test(TestCase):

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

查看mymodule直接导入函数external_function。因此,您需要模拟mymodule.external_function,因为这是在执行method1时将被调用的函数。