使用 python unittest 抽象测试用例 [英] abstract test case using python unittest
问题描述
是否可以创建一个抽象的TestCase
,它会有一些test_* 方法,但是这个TestCase
不会被调用,这些方法只会在子类?我想我将在我的测试套件中有一个抽象的 TestCase
并且它将为单个接口的几个不同实现进行子类化.这就是为什么所有的测试方法都是一些,只有一个,内部方法的变化.我怎样才能以优雅的方式做到这一点?
Is it possible to create an abstract TestCase
, that will have some test_* methods, but this TestCase
won't be called and those methods will only be used in subclasses? I think I am going to have one abstract TestCase
in my test suite and it will be subclassed for a few different implementation of a single interface. This is why all test methods are the some, only one, internal method changes. How can I do it in elegant way?
推荐答案
我不太明白你打算做什么 --经验法则是不要对测试聪明"-把它们放在那里,简单地写下来.
I didn't quite understand what do you plan to do -- the rule of thumb is "not to be smart with tests" - just have them there, plain written.
但是为了实现你想要的,如果你从 unittest.TestCase 继承,每当你调用 unittest.main() 你的抽象"类将被执行 - 我认为这是你想要避免的情况.
But to achieve what you want, if you inherit from unittest.TestCase, whenever you call unittest.main() your "abstract" class will be executed - I think this is the situation you want to avoid.
只需这样做:创建从对象"而不是从 TestCase 继承的抽象"类.对于实际的具体"实现,只需使用多重继承:从 unittest.TestCase 和抽象类继承.
Just do this: Create your "abstract" class inheriting from "object", not from TestCase. And for the actual "concrete" implementations, just use multiple inheritance: inherit from both unittest.TestCase and from your abstract class.
import unittest
class Abstract(object):
def test_a(self):
print "Running for class", self.__class__
class Test(Abstract, unittest.TestCase):
pass
unittest.main()
update:先颠倒继承顺序 - Abstract
以便其定义不会被 TestCase
默认值覆盖,并在注释中指出如下.
update: reversed the inheritance order - Abstract
first so that its defintions are not overriden by TestCase
defaults, as well pointed in the comments bellow.
这篇关于使用 python unittest 抽象测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!