考虑以下示例:
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
我的任务是编写单元测试A
,B
以及C
类(特别是do_stuff
)。
但是,A
如果我不能直接使用某些方法,该如何测试类呢?我应该只测试B
和C
类(具有的实现helper_method
),还是应该有通用的方法来测试Python中的抽象类?
至少就语言而言,您实际上没有抽象的基类。没有什么阻止您实例化它。
a = A()
如果您使用abc
模块来定义无法实例化的类:
class A(metaclass=abc.ABCMeta):
...
那么您可以A
通过覆盖其抽象方法集来实现实例化:
A.__abstractmethods__ = frozenset()
a = A()
# test away
无论哪种情况,您仍然可以测试抽象方法是否引发了 NotImplementedError
try:
a.helper_method()
except NotImplementedError:
print("Test passed")
else:
print("Test failed")
或根据需要测试其默认实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句