Example Python codes

สมมติมี def ของการคำนวณ multiply หาผลคูณของสองตัวเลข

1 def multiply(x, y):
2     return x * y

ในการใช้ unittest [1] ต้อง import unittest แล้วเขียนคลาสที่เป็น subclass ของ unittest.TestCase ดังตัวอย่าง

 1 import unittest
 2 from mymath import multiply
 3 
 4 class TestUM(unittest.TestCase):
 5 
 6     def setUp(self):
 7         pass
 8 
 9     def test_numbers_3_4(self):
10         self.assertEqual( multiply(3,4), 12)
11 
12     def test_strings_a_3(self):
13         self.assertEqual( multiply('a',3), 'aaa')
14 
15 if __name__ == '__main__':
16     unittest.main()

สำหรับตัวอย่างอื่นๆ ดูที่ unittesttut [2], Stackoverflow - Writing unit tests in Python [3] มีคำอธิบายและคำแนะนำในเรื่องการใช้ unittest ที่น่าสนใจ

เอกสารเกี่ยวกับ doctest

[1]เอกสาร Python unit testing tutorial ของ Python
[2]คำแนะนำการใช้ unittest เบื้องต้น โดย Corey Goldberg, unittesttut
[3]unitteststackov บน Stackoverflow