其他模块的模拟功能 [英] Mock function from other module

查看:97
本文介绍了其他模块的模拟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个python文件:

I have two python files:

function.py:

function.py:

def foo ():
    return 20

def func ():
    temp = foo()
    return temp

和嘲笑.py:

 from testing.function import *
 import unittest
 import mock
 class Testing(unittest.TestCase):

 def test_myTest(self):

     with mock.patch('function.func') as FuncMock:
         FuncMock.return_value = 'string'

         self.assertEqual('string', func())

我想模拟func,但是没有积极的结果.我有AssertionError:'string'!= 20.我应该怎么做才能正确模拟它?如果我执行了mock.patch('func'),则出现TypeError:需要有效的目标进行修补.您提供了:"func".如果我将func移到嘲讽.py并调用foo:function.foo(),它将正常工作.但是,当我不想将功能从function.py移到嘲讽.py时,该怎么办?

I want to mock func, but with no positive result. I have AssertionError: 'string' != 20. What should I do to mock it correctly ? If I do mock.patch ('func') I have TypeError: Need a valid target to patch. You supplied: 'func'. If I move func to mocking.py and call foo: function.foo() it works correctly. But how to do it when I don't want to move functions from function.py to mocking.py ?

推荐答案

在调用实际函数但希望模拟该函数中的某些函数调用时,模拟很有用.在您的情况下,您打算模拟func,并且希望通过执行func()直接调用该模拟函数.

Mocking is useful when you're calling an actual function but you want some function calls inside that function to be mocked out. In your case you're aiming to mock func and you wish to call that mocked function directly by doing func().

但是,这是行不通的,因为您正在模拟function.func,但是您已经将func导入了测试文件.因此,您要调用的func()是一个实际函数,它与模拟的FuncMock不同.尝试致电FuncMock(),您会得到预期的结果.

However that won't work because you're mocking function.func but you've imported func already into your test file. So the func() that you're calling is an actual function, it's not the same as the mocked FuncMock. Try calling FuncMock() and you'll get the result as expected.

以下内容应该可以工作,并且可以让您知道可以做什么:

The following should work and it gives you an idea of what can be done:

from testing.function import func
import unittest
import mock

class Testing(unittest.TestCase):

    def test_myTest(self):

        with mock.patch('testing.function.foo') as FooMock:
            FooMock.return_value = 'string'

            self.assertEqual('string', func())

这篇关于其他模块的模拟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆