Unit Testing คืออะไร
Unit Testing คือการทดสอบซอฟต์แวร์ที่ทดสอบแต่ละคอมโพเนนต์ (unit) แยกกัน เพื่อให้แน่ใจว่าแต่ละส่วนทำงานถูกต้องตามที่คาดไว้ ทำโดยนักพัฒนาในช่วง coding phase
Python Unit Testing ด้วย unittest
Python มี module unittest ในตัวสำหรับ unit testing
การใช้งาน
import unittest
ตัวอย่าง: ทดสอบฟังก์ชันคำนวณพื้นที่สี่เหลี่ยม
area.py
def area(a):
return (a * a)
unit_test.py
from area import *
import unittest
class TestArea(unittest.TestCase):
def test_area(self):
self.assertAlmostEqual(area(5), 25)
self.assertAlmostEqual(area(3), 9)
self.assertAlmostEqual(area(4), 16)
รันการทดสอบ
python -m unittest unit_test.py
ผลลัพธ์เมื่อผ่าน
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
ผลลัพธ์เมื่อล้มเหลว
F
======================================================================
FAIL: test_area (unit_test.TestArea)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unit_test.py", line 7, in test_area
self.assertAlmostEqual(area(5), 25)
AssertionError: 10 != 25 within 7 places (15 difference)
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Assert Methods สำคัญ
- assertEqual(a, b): a == b
- assertAlmostEqual(a, b): a ≈ b (floating point)
- assertTrue(x), assertFalse(x)
- assertRaises(Error, func): คาดหวัง exception
ประโยชน์
- พบ bug ได้เร็ว
- ทำให้โค้ด maintainable
- เป็น documentation ของ behavior ที่คาดหวัง
- ช่วย refactoring ได้ปลอดภัย