0
1

More than 3 years have passed since last update.

unittest覚書

Last updated at Posted at 2020-08-26

unittestとは

単体テスト(ユニットテストと呼ばれることもあります)は、プログラムを構成する比較的小さな単位(ユニット)が個々の機能を正しく果たしているかどうかを検証するテストです。
通常、関数やメソッドが単体テストの単位(ユニット)となります

単体テスト(ユニットテスト)とは | ソフトウェアの検証の種類 | テクマトリックス株式会社

要するに関数とかがちゃんと動いているかチェックするテストである。
先に関数の振る舞いを決めてテストを書いてから関数の実物を書くのがテスト駆動開発-TDD(あっているか自信なし)

どんな風に書くん?

import unittest
import <テストしたい関数とか>

class Test<テストしたい(ry>(unittest.TestCase): # 名前は重要ではないけどunittest.TestCaseを引き継ぐのは必須
    def test_<テストする関数>(self): # test_*と書くと自動でテストだと認識してくれるらしい
        """テストの説明
        """
        self.assertEqual(出てくるべき答え, <テストしたい関数>(引数))

基本的にはこんな感じでいいらしい

こんな感じのディレクトリ構成だとする

projectroot
├── src
│   └── hoge.py
└── test
    └── test_hoge.py

hoge.pyをテストするtest_hoge.pyがある

hoge.py

def foo(a: int, b: int) -> int:
    return a + b

def bar(a: int, b: int) -> int:
    return a - b
test_hoge.py
import unittest
from src import hoge

class TestHoge(unittest.TestCase):
    def test_foo(self):
        """fooのテスト
        """
        expected = 2
        actual = hoge.foo(1, 1)
        self.assertEqual(expected, actual)

    def test_bar(self):
        """barのテスト
        """
        expected = 0
        actual = hoge.bar(1, 1)
        self.assertEqual(expected, actual)

testの実行は次のようになる

python -m unittest discover -s test -v

projectroot直下でtest内のコードを実行している

実行結果
test_foo (test_hoge)
fooのテスト ... ok
test_bar (test_hoge)
barのテスト ... ok

----------------------------------------------------------------------
Ran 1 test in 0.003s

OK
0
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
0
1