# 單元測試 Unit Test 如果我們今天想要測試一個函數是否如預期的運作,那麼我們可以用單元測試。 最簡單版本: ```python= def add(x,y): return x+y if add(1,2) == (1+2): print('測試通過') else: print('測試不通過') ``` 現在,我們用`assert`來做: ```python= def add(x,y): return x+y assert add(1,2) == 3 # 什麼都不會發生 assert add(1,2) == 4, "錯誤" # AssertionError: 錯誤 ``` 這個東西你平常可以在寫程式的時候就使用它。例如你寫了某個函數,然後想確定是否如你所料,就可以寫在中間。如果他如你所料,那麼不會發生任何事情,程式順利執行; 反之,如果他不如你所料,程式就會出現錯誤訊息。你就更快速地知道哪邊出錯。 再來,我們利用`unittest`這個模組來進行單元測試: ```python= def add(x,y): return x+y import unittest class SomeTest(unittest.TestCase): def test_add(self): self.assertEqual(add(1,2), 3) if __name__ == '__main__': unittest.main() ``` ![](https://i.imgur.com/xRlaAYu.png) 進行一些小變化: ```python= import unittest import random def add(x,y): return x+y class TestSomething(unittest.TestCase): def test_add(self): x, y = random.randint(1,1000), random.randint(1,1000) self.assertEqual(add(x,y), x+y) def test_add_error(self): self.assertEqual(add(1,2), 4) if __name__ == '__main__': unittest.main() ``` ![](https://i.imgur.com/A0g4FpW.png) ## Furthermore 寫單元測試可以用來做「Test Driven Development」, 請看[這篇文章](https://tw.alphacamp.co/blog/tdd-test-driven-development-example)。 以下進行練習(看到這邊的人來幫我把文章的練習改成Python xD) [小練習題](https://tddmanifesto.com/exercises/) [練習題](https://tdd.mooc.fi/exercises#exercise-1-small-safe-steps)