如何模拟在其他函数中创建了类实例的类方法?

时间:2019-06-25 06:32:39

标签: python unit-testing mocking

我正在尝试模拟使用使用带有变量的类方法的函数,但是直到调用main方法时才创建对象。

我正在测试的脚本:

import testscript as script

def script_function():
    result = object.function1(2)
    print(result)

def main():
    global object
    object = script.MathTest("my name", 5)
    script_function()

if __name__ == "__main__":
    main()

帮助类

def sum1(num1, num2):
    return num1 +num2

class MathTest:
    def __init__(self, name, num1):
        self.name = name
        self.num1 = num1

    def get_num1(self):
        return self.num1

我的测试脚本

import pytest
import script
import mock
import testscript

@mock.patch('script.script.MathTest.function1')
def test_function(mock_func):
    mock_func.return_value = 99
    assert script.script_function() == 99

测试结果:

mock_func = <MagicMock name='function1' id='56369872'>

    @mock.patch('script.script.MathTest.function1')
    def test_function(mock_func):
        mock_func.return_value = 99
>       assert script.script_function() == 99

test.py:9:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    def script_function():
>       result = object.function1(2)
E       AttributeError: type object 'object' has no attribute 'function1'

script.py:4: AttributeError

我知道它不知道什么是对象,但是我不确定如何模拟它。

0 个答案:

没有答案