【问题标题】:How can I mock an external function within a method in a class如何在类的方法中模拟外部函数
【发布时间】:2013-11-28 03:24:48
【问题描述】:

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

我在 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?'''

【问题讨论】:

    标签: python unit-testing mocking python-mock


    【解决方案1】:

    你会写:

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

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

    【讨论】:

    • 谢谢。不知何故,我在嘲笑错误的东西。你让我挺直了。
    猜你喜欢
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多