为抽象类编写单元测试

2024-04-27 15:05:23 发布

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

考虑这个例子:

class A:
    def do_stuff(self):
        # ...
        some_var = self.helper_method()
        # ...

    def helper_method(self):
        # This method must be implemented by subclass
        raise NotImplementedError()

class B(A):
    def helper_method(self):
        # implementation for class B

class C(A):
    def helper_method(self):
        # implementation for class C

我的任务是为AB和{}类编写单元测试(尤其是do_stuff)。在

但是如果我不能直接使用某些it方法,如何测试A类呢? 我应该只测试BC类(它们有helper_method的实现) 或者,在Python中有测试抽象类的通用方法?在


Tags: 方法selfhelperforvardefsomethis
3条回答

你应该测试逻辑,而不是实现。A的do\u stuff()方法本身没有逻辑,对吗?它能做什么取决于你是在处理B还是C。相反,在我看来,测试B和C的do\u stuff()方法更有意义——你知道它们到底应该做什么。在

do_stuff存在于A上,因此请在A上测试它。helper方法存在于具体类上,因此在那里测试它们。您可以使用^{}模块临时修补抽象类,以便它能与您的测试一起工作,还可以修补抽象方法以返回特定的值,这样它的逻辑就不会被测试。考虑到这些,这就是我测试抽象类的方法。在

给出一些抽象类:

from abc import abstractmethod, ABC

class MyAbstract(ABC):
    def concrete_method(self):
        i = self.abstract_method()
        return i ** 2

    @abstractmethod
    def abstract_method(self):
        """return some int"""
        pass

这就是我要测试它的方法。在

^{pr2}$

你没有真正的抽象基类,至少就语言而言。没有什么能阻止你实例化它。在

a = A()

如果您使用abc模块来定义无法实例化的类:

^{pr2}$

然后,您可以通过重写A的一组抽象方法使其成为可实例化的:

A.__abstractmethods__ = frozenset()
a = A()
# test away

无论哪种情况,您仍然可以测试抽象方法是否引发NotImplementedError

try:
    a.helper_method()
except NotImplementedError:
    print("Test passed")
else:
    print("Test failed")

或者根据需要测试其默认实现。在

相关问题 更多 >