【问题标题】:Mock function from other module来自其他模块的模拟功能
【发布时间】:2014-12-04 19:49:50
【问题描述】:

我有两个 python 文件:

函数.py:

def foo ():
    return 20

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

和 mocking.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: Need a valid target to patch。你提供了:'func'。如果我将 func 移动到 mocking.py 并调用 foo: function.foo() 它可以正常工作。但是当我不想将函数从 function.py 移动到 mocking.py 时怎么办?

【问题讨论】:

    标签: python unit-testing mocking python-unittest python-mock


    【解决方案1】:

    当您调用实际函数但您希望在该函数中模拟一些函数调用时,Mocking 很有用。在您的情况下,您的目标是模拟 func,并且您希望通过执行 func() 直接调用该模拟函数。

    但这不起作用,因为您正在模拟 function.func,但您已经将 func 导入到您的测试文件中。所以你调用的func() 是一个实际的函数,它与模拟的FuncMock 不同。尝试调用FuncMock(),你会得到预期的结果。

    以下应该可以工作,它让您了解可以做什么:

    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())
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多