すべてのテストケースのティアダウンで呼び出す必要がある関数 removeElements() があります。各テストケースで関数呼び出しをコピーするのではなく、分解時にこの関数を自動的に呼び出す方法はありますか?
2 に答える
2
メソッドについてはすでに知っているtestCase
ようで、実装を継承する方法も既に知っているようです。唯一欠けているのは、実装を継承しながらカスタマイズを許可する方法だけです。
tearDown
これを行う最も簡単な方法は、フックを実装する中間クラスまたは mixin クラスを作成することです。たとえば、次のようなテスト ケースを書いているとします。
class MyTestCase(unittest.TestCase):
def tearDown(self):
print('Tearing down {}'.format(self))
…しかし、あなたはそれらすべてに電話をかけたいremoveElements
.
この中間クラスを定義します。
class ElementRemovingTestCase(unittest.TestCase):
def tearDown(self):
self.removeElements()
そして、代わりにこのようにケースを書きます:
class MyTestCase(ElementRemovingTestCase):
def tearDown(self):
super(MyTestCase, self).tearDown()
print('Tearing down {}'.format(self))
各テスト ケースで 1 行のコードを節約できるように、メソッド解決チェーンを省略したくないtearDown
場合は、代わりに新しいフック プロトコルを定義できます。
class ElementRemovingTestCase(unittest.TestCase):
def tearDown(self):
self.removeElements()
self.additionalTearDown()
class MyTestCase(ElementRemovingTestCase):
def additionalTearDown(self):
print('Tearing down {}'.format(self))
また、Python での OO のその他の通常のオプションは、どれだけクレイジーになりたいとしても、ここで機能します。
for name, case in inspect.getmembers(sys.modules[__name__],
lambda cls: issubclass(cls, unittest.TestCase)):
real_tearDown = case.tearDown
def tearDown(self):
self.removeElements()
real_tearDown(self)
case.tearDown = real_tearDown
于 2013-04-26T17:51:06.017 に答える