【问题标题】:Unable to raise Exception while mocking a whole python class in unittest在单元测试中模拟整个 python 类时无法引发异常
【发布时间】:2020-07-15 13:11:20
【问题描述】:

这是原来的类:

class Original(object):
    def __ init__(self, path):
        self.xml = None
        self.path = path
        self.convert() # <----- I can't modify anything in my class

    def convert(self):
        #some code here
        self.xml = external_api_call # <------------this generates objects for this property
        self.transform()

    def transform(self):
        #some code
        if not self._xml:
            raise Exception('None value')
        for project in self.xml.projects:
            try:
                value = getattr(project, "name")
            except AttributeError:
                raise Exception('AttributeError')
            print('Yes it worked')

因此,我想要 100% 的覆盖率,我尝试为外部 api 调用生成模拟对象。不幸的是,在使用模拟对象时,它永远不会引发任何异常。

with mock.patch('something.Original', autospec=True) as mock_object:
    mock_object.xml = None
    mock_object.transform()

它应该生成一个异常,但它没有。我也尝试过不同的方法,例如模拟对象的 side_effect 属性。

mock_object._xml.return_value

【问题讨论】:

  • 不修补Original,只修补external_api_call,如with mock.patch("something.external_api_call", lamda *args, **kws: None):

标签: python unit-testing mocking pytest


【解决方案1】:
@patch('something.Original')
def test_case_1(Original):
    Original.xml.side_effect = Exception()
    Original.transform()

【讨论】:

    猜你喜欢
    • 2023-02-06
    • 2022-07-08
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多