如何在模拟对象中存根方法?

2024-10-02 16:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要测试代码片段(例如,来自classUnderTestClass):

def _method_to_test(self)
    ...

    ParsingObject = MyParsingClass()
    if not ParsingObject.parse_string(some_string):
        self.logger.error('Parsing data has failed.')
        return False
    return ParsingObject

不管我怎么尝试,都不能覆盖最后一个return语句-return ParsingObject,所以我对parse_string()方法的模仿一定有问题。在

我试过Python测试教程中的语句:

^{pr2}$

但不幸的是只有:

AssertionError: False is not an instance of class 'my_app.myParsingClass.MyParsingClass'

更新:谢谢。我听从你的建议,所以重新写一点:

    with patch('...') as ParseMock:
             instance = ParseMock.return_value
             ParseMock.parse_string.return_value = True
             res = tested_module.UnderTestClass._method_to_test(UnderTestClassMock)
             assert myParsingClass.MyParsingClass() is instance
             assert myParsingClass.MyParsingClass() is res

但最后一行还是有断言错误。在

编辑:我需要某种依赖注入机制/框架吗?在


Tags: toinstancetestselffalsestringreturnparse
2条回答

您应该模拟实例方法parse_string,而不是类方法。在

In [22]: import mock

In [23]: ParseMock = mock.Mock()

In [24]: instance = ParseMock.return_value

In [25]: instance.parse_string.return_value = True

In [26]: parser = ParseMock()

In [27]: parser.parse_string("foo")
Out[27]: True

您需要设置parseMock的返回值,而不是parseInstance:

parseMock.parse_string.return_value = True

您还需要在断言之后停止()修补程序

相关问题 更多 >