1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

unittestとは

1
Last updated at Posted at 2021-11-12

Pythonでのunittestの使い方についてまとめる。

unittestとは

unittestとは、Pythonの標準モジュールとして提供されているテストフレームワーク。
unittestを利用することで、複数のテストを同時にできることや、同条件で何度も行えるなどのメリットがある。

unittestの使い方

unittestのテストプログラムの基本的な書き方は以下となる。まず、ファイル名については、「test_<テスト対象モジュール>.py」とする。

  1. unittestモジュールをインポートする。
  2. テストクラスは、クラス名を「Test<テスト対象クラス名>」とし、unittest.TestCaseを継承して作成する。
  3. テストメソッドは、メソッド名を「test_<テスト対象メソッド名>」とし、テストケースを記述する。テストは unittestで提供されているメソッド(assertEqual()やassertTrue()など)を使用して判定を行う。  
    提供されているassertメソッドについては、公式ドキュメントを参照(公式ドキュメント
    4.unittest.main()でテストを実行する。

例として、calculator.pyのメソッドをテストするテストプログラムtest_calculator.pyは以下のように書くことができる。

calculator.py
class Calculator:
    def multiply(self,a,b):
        return a * b
test_calculator.py
# 1. unittestをインポート
import unittest
from calculator import Calculator

# 2. クラス名を「Test<テスト対象クラス名>」とし、unittest.TestCaseを継承
class TestCalculator(unittest.TestCase):

    calculator = Calculator()
    # 3. メソッド名を「test_<テスト対象メソッド名>」とし、テストケースを記述
    def test_multiply(self):
        calculator = Calculator()
        # テストコードの記述
        self.assertEqual(6, calculator.multiply(2,3))

# 4.unittest.main()で実行
if __name__ == "__main__":
    unittest.main()
実行結果
$ python test_calculator.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?