LoginSignup
0
0

More than 1 year has passed since last update.

pythonのunittestを使う方法

Last updated at Posted at 2022-02-05

pythonのunittestを作るときいつもVSCodeで動かないのが悔しいのでメモを残す

unittestは基本的にこのような形のソースをで書く

import unittest

class AAA( unittest.TestCase ):
    def test_xxxx(self):
        ...

if __name__ == '__main__':
    unittest.main()

ポイントは

  • クラスは unittest.TestCase クラスを継承すること
  • メソッドは test_ ではじめること(多分、引数はないほうがいい)

最後のif __name__ ==以降はこのファイルを直で起動したときに実行できるようにするためのもの。

次に私はいつもここで困るのだが、フォルダ構成。私はpythonに慣れていないのでモジュールの動きがわからず、「???」となったのでこのメモを残すことにした

test
  ├ testsuite
  │  ├ __init__.py
  │   └ AAA_test.py
  │
  ├ test_root.py
  └ __init__.py

のように各フォルダにinit.pyとするとパッケージ?のルールに従ってtest_AAA.pyのを見つけてくれる。

上記の構成なら python3 -m unittest で認識してくれる。

VSCodeの場合、
image.png

をクリックして

image.png

の Configure Python Testsをクリック

image.png

unittestを選択して下の「test」を選択
image.png

テストファイル名のパターンを聞いてくるので4番目の「test_*.py」を選択する。

スクリーンショット 2022-02-05 19.36.07.png

こうなればOK。
image.png

スクショミスで上2つが実行ずみになっているのはご愛嬌。

参考: https://docs.python.org/ja/3/library/unittest.html

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