Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Unit Testing ใน Python ด้วย unittest Module

ในบทช่วยสอนนี้ เราจะเรียนรู้ Unit Testing ด้วยโมดูลสร้างใน unittest การทดสอบเป็นสิ่งสำคัญในการพัฒนาซอฟต์แวร์ ช่วยค้นพบบั๊กก่อนปล่อย production

Unit Testing คืออะไร?

ยกตัวอย่างระบบ Login แต่ละฟิลด์ (username, password) เป็น "หน่วย" (unit) การทดสอบการทำงานของแต่ละหน่วยแยกกัน เรียกว่า Unit Testing

โครงสร้างพื้นฐานของ unittest

import unittest

class SampleTest(unittest.TestCase):
    def test_something(self):
        # test method ต้องขึ้นต้นด้วย 'test'
        self.assertTrue(True)

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

Output เมื่อผ่านทั้งหมด

.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK

ทดสอบ String Methods

ตัวอย่างทดสอบเมธอดสตริงต่างๆ

import unittest

class TestingStringMethods(unittest.TestCase):
    
    def test_string_equality(self):
        # assertEqual: ตรวจสอบค่าเท่ากัน
        self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')
    
    def test_string_case(self):
        self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')
    
    def test_is_string_upper(self):
        # assertTrue: ตรวจสอบว่าเป็น True
        self.assertTrue('TUTORIALSPOINT'.isupper())
        # assertFalse: ตรวจสอบว่าเป็น False
        self.assertFalse('TUTORIALSpoint'.isupper())

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

Output เมื่อผ่านทั้งหมด

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK

Output เมื่อมี Test ล้มเหลว (Fail)

# เปลี่ยน 'TUTORIALSPOINT' -> 'TUTORIALSPOINt' (มีตัวเล็กท้าย)
self.assertTrue('TUTORIALSPOINt'.isupper())
======================================================================
FAIL: test_is_string_upper (__main__.TestingStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 21, in test_is_string_upper
    self.assertTrue('TUTORIALSPOINt'.isupper())
AssertionError: False is not true
----------------------------------------------------------------------
Ran 3 tests in 0.016s
FAILED (failures=1)

Assert Methods ที่ใช้บ่อย

Methodความหมาย
assertEqual(a, b)a == b
assertNotEqual(a, b)a != b
assertTrue(x)x is True
assertFalse(x)x is False
assertIs(a, b)a is b (same object)
assertIsNone(x)x is None
assertIn(a, b)a in b
assertRaises(Error, func)func 拋出 Error

รัน Test แบบ Verbose

# command line
python -m unittest test_module -v

# หรือในโค้ด
unittest.main(verbosity=2)

สรุป

unittest เป็น framework ทรงพลังที่มาพร้อม Python ให้ใช้งานทันที การเขียน test ควรครอบคลุม edge cases และรันบ่อยๆ (CI/CD) เพื่อคุณภาพโค้ดที่ดี


หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็นครับ