Pythonのunittestの使い方を確認します。
環境
- Python 3.8.5
サンプルプログラム
公式ドキュメントを参考。
テスト対象のプログラム
テスト対象とするコードを記述。
hololive.py
class HololiveMember(): def __init__(self, nickname): self.nickname = nickname def get_hello(self): msg = f'Hello, {self.nickname}!' return msg
テストプログラム
テストプログラムとなるコードを記述。実際テストしているのは test_get_hello()
だけ。
test_hololive.py
import unittest import hololive class HololiveMemberTest(unittest.TestCase): def setUp(self): """ Method called to prepare the test fixture. This is called immediately before calling the test method """ self.sakura_miko = hololive.HololiveMember('Mikochi') def tearDown(self): """ Method called immediately after the test method has been called and the result recorded. """ pass @unittest.skip('skipping message') def test_nothing(self): """ Unconditionally skip the decorated test. """ self.fail('should not happen') def test_get_hello(self): msg = self.sakura_miko.get_hello() self.assertEqual(msg, 'Hello, Mikochi!') if __name__ == 'main': unittest.main()
unittestの書き方。
- テスト用クラスは、
unittest.TestCase
のサブクラスとして作成 test
からはじまるメソッドをすべて実行してくれる- setUp() は、各テスト実行の前に、必ず実行してくれる
unittest.TestCase
のインスタンスメソッド - tearDown() は、各テスト実行の後に、必ず実行してくれる
unittest.TestCase
のインスタンスメソッド - unittest.skip(reason) でデコレートされたテストは、無条件でスキップされる
利用可能なアサートメソッドたち。
テストの実行
コマンドラインより実行。
$ python3 -m unittest -v test_hololive.py test_get_hello (test_hololive.HololiveMemberTest) ... ok test_nothing (test_hololive.HololiveMemberTest) Unconditionally skip the decorated test. ... skipped 'skipping message' ---------------------------------------------------------------------- Ran 2 tests in 0.002s OK (skipped=1)