【问题标题】:How to write Unittest for subclass while mocking base class?如何在模拟基类时为子类编写单元测试?
【发布时间】:2019-03-07 07:00:04
【问题描述】:

我想在模拟 Base 时为 Subclass 编写测试,因为 Base 来自外部库。鉴于我们修改了基类中的所有可调用对象,我该如何模拟它。

class SubClass(Base):
    def __init__(self, *args, **argv):
        super().__init__(*args, **argv)

        for attr_name in Base.__dict__:
            attr = getattr(self, attr_name)
            if callable(attr):
                setattr(self, attr_name, functools.partial(__class__.sanity_check, attr))

    @classmethod
    def sanity_check(func):
        txt = func()
        if 'banned_word' in txt:
            raise Exception('Device has banned word on it!')
        return txt

【问题讨论】:

  • 模拟整个基类并不是一个好习惯。你真正想测试什么?

标签: python python-unittest python-unittest.mock


【解决方案1】:

您不需要模拟整个类,模拟其中的方法就足够了。顺便说一句,我必须将 sanity_check 声明为静态才能使您的示例代码正常工作。

只看一个微不足道的基类:

class Base:
    def a(self):
        return "foo"
    def b(self):
        return "bar"

我们可以在创建子类对象之前轻松地模拟方法a

with unittest.mock.patch('module.Base.a', return_value='banned_word') as p:
    x = SubClass()
    x.a()

按预期提高:

Traceback (most recent call last):
  File "###", line #, in <module>
    x.a()
  File "###", line ##, in sanity_check
    raise Exception('Device has banned word on it!')
Exception: Device has banned word on it!

module是声明Base的模块的名称,我只是用__main__进行测试...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2013-01-28
    • 2017-09-04
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多