- A testcase is created by subclassing unittest.TestCase.
- Individual tests are defined with methods whose names start with the letters "test". This naming convention informs the test runner about which methods represent tests.
- Following is a typical example of unit test:
# PythonUnitTest.py
import unittest
class Sort(unittest.TestCase):
def setUp(self):
self.nums = [10,20,30,40]
def tearDown(self):
self.nums = None
def test_blank(self):
self.nums = None
self.assertEqual(self.nums, None)
def test_len(self):
self.assertEqual(len(self.nums), 4)
def test_contains(self):
self.assertTrue(10 in self.nums)
self.assertTrue(20 in self.nums)
self.assertTrue(30 in self.nums)
self.assertTrue(40 in self.nums)
self.assertIn(40, self.nums)
self.assertNotIn(60, self.nums)
def main():
unittest.main()
if __name__ == '__main__':
main()
Execute the tests like this:
python PythonUnitTest.py --verbose
Skipping Test Cases
@unittest.skip("demonstrating skipping")
def test_nothing(self):
self.fail("shouldn't happen")
Assert Methods
- assertEqual(a, b)
- assertNotEqual(a, b)
- assertTrue(x)
- assertFalse(x)
- assertIs(a, b)
- assertIsNot(a, b)
- assertIsNone(x)
- assertIsNotNone(x)
- assertIn(a, b)
- assertNotIn(a, b)
- assertIsInstance(a, b)
- assertNotIsInstance(a, b)
- assertGreater(a, b)
- assertGreaterEqual
- assertLess
- assertLessEqual
- assertRegexpMatches(s, r)
- assertItemsEqual(a, b)
- assertDictContainsSubset(a, b)
Useful Links