LoginSignup
0
0

More than 3 years have passed since last update.

unittest

Last updated at Posted at 2020-03-22
calculation.py
class Cal(object):
    def add_num_and_double(self, x, y):

        if type(x) is not int or type(y) is not int:
            raise ValueError
        result = x + y
        result *= 2
        return result

calculation.pyをunittestでテストします

test_calculation.py
import unittest
import calculation

release_name = 'lesson2'

class CalTest(unittest.TestCase):

    #テストが走る前に呼ばれる
    def setUp(self):
        print('set up')
        self.cal = calculation.Cal()

    #テスト終了後に呼ばれる
    def tearDown(self):
        print('clean up')
        del self.cal

    #@unittest.skip('skip')などでテストをスキップさせることもできますが、今回はスキップはしません
    @unittest.skipIf(release_name == 'lesson', 'skip!')
    def test_add_num_and_double(self):#test_メソッド名の形にする
        #cal = calculation.Cal()
        self.assertEqual(self.cal.add_num_and_double(1, 1), 4)

    #例外テスト
    def test_add_num_and_double_raise(self):
        #cal = calculation.Cal()
        with self.assertRaises(ValueError):
            self.cal.add_num_and_double('1', '1')

#pycharmの場合は不要
#if __name__ == '__main__':
#    unittest.main()

setupとteardownがそれぞれ2回呼ばれていることがわかります。

出力
PASSED             [ 50%]set up
clean up
PASSED       [100%]set up
clean up
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