Unit Test
單元測試有一個通用模式 AAA原則,理解了就可以開始實作
- Arrange : 初始化物件、要用到的參數
- Act : 呼叫要測試的方法
- Assert : 驗證測試結果
Python Unit Test
unittest — Unit testing framework,下面是官方給的範例
import unittest
class TestStringMunittestethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
unittest.main() 會執行所有 test_ 開頭的 function,主要判斷的 function 是 assert- assertEqual - 確認是否符合期望的值
- assertTrue、assertFalse - 確認是否符合期望的判斷
- assertRaise - 確認是否有特定 exception raise
D:\temp\JunYe\MyPython\Python3\LeetCode\UnitTest>python3 UnitTest.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
D:\temp\JunYe\MyPython\Python3\LeetCode\UnitTest>
然後就是我自己的實作,拿 LeetCode - 0736 當範例
import unittest
import Solution
class TestMethods(unittest.TestCase):
def test_case1(self):
# Arrange
testclass = Solution.Solution()
spec = '(add 1 2)'
# Act & Assert
self.assertEqual(testclass.evaluate(spec), 3)
def test_case2(self):
# Arrange
testclass = Solution.Solution()
spec = '(mult 3 (add 2 3))'
# Act & Assert
self.assertEqual(testclass.evaluate(spec), 15)
def test_case3(self):
# Arrange
testclass = Solution.Solution()
spec = '(let x 2 (mult x 5))'
# Act & Assert
self.assertEqual(testclass.evaluate(spec), 10)
if __name__ == '__main__':
unittest.main()
參考資料 :
0 意見:
張貼留言