Module unittest built-in của Python cung cấp framework testing xUnit style: test case, test suite, fixture (setUp/tearDown), assertions.
Cấu trúc cơ bản
- Kế thừa
unittest.TestCase. - Tên phương thức test bắt đầu bằng
test_. - Sử dụng các assert method:
assertEqual,assertTrue,assertFalse,assertRaises, v.v. - Chạy bằng
unittest.main()hoặcpython -m unittest.
Ví dụ 1: Test case đơn giản
import unittest
class SampleTest(unittest.TestCase):
def test_always_pass(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()Kết quả
Ran 1 test in 0.001s OK
Ví dụ 2: Test các phương thức string
import unittest
class TestStringMethods(unittest.TestCase):
def test_string_equality(self):
self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')
def test_string_case(self):
self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')
def test_is_upper(self):
self.assertTrue('TUTORIALSPOINT'.isupper())
self.assertFalse('TUTORIALSpoint'.isupper())
if __name__ == '__main__':
unittest.main()Kết quả
Ran 3 tests in 0.001s OK
Các assert method phổ biến
| Method | Kiểm tra |
|---|---|
assertEqual(a, b) | a == b |
assertNotEqual(a, b) | a != b |
assertTrue(x) | bool(x) is True |
assertFalse(x) | bool(x) is False |
assertIs(a, b) | a is b (identity) |
assertIsNone(x) | x is None |
assertIn(a, b) | a in b |
assertRaises(Error, func, *args) | func(*args) ném Error |
Fixture: setUp() và tearDown()
class TestWithFixture(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3]
print("setUp called")
def tearDown(self):
self.data = None
print("tearDown called")
def test_length(self):
self.assertEqual(len(self.data), 3)
def test_sum(self):
self.assertEqual(sum(self.data), 6)Mỗi test method chạy setUp trước, tearDown sau. Cách ly test case.
Chạy test từ command line
python -m unittest test_module.py python -m unittest test_module.TestClass.test_method python -m unittest discover # tự động tìm test_*.py
Kết luận
unittest đủ mạnh cho unit testing cơ bản. Cho dự án lớn, cân nhắc pytest (cú pháp đơn giản hơn, fixture mạnh, plugin phong phú). Viết test sớm (TDD) để code chất lượng, dễ refactor.