UnitTest
Python自带unittest标准库。在unittest中,通过assert开头的断言方法,来检查返回的结果是否符合预期
# 编写一个待测试的函数
def just_do_it(text):
return text.capitalize()
import unittest # Python的内置标准库,依赖于Java的JUnit
class TestCap(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_one_word(self):
text = 'duck'
result = just_do_it(text)
self.assertEqual(result, 'Duck')
def test_multiple_words(self):
text = 'a veritable flock of ducks'
result = just_do_it(text)
self.assertEqual(result, 'A Veritable Flock Of Duck')
if __name__ == '__main__':
unittest.main()
setUp()
方法会在每个测试方法执行之前执行,常用来进行一些初始化和分配外部资源的操作tearDown()
方法则在每个测试方法执行之后执行,常用来回收外部资源
断言方法
assertEqual(first, second, msg=None)
assertNotEqual(first, second, msg=None)
assertTrue(expr, msg=None)
assertFalse(expr, msg=None)
assertIs(first, second, msg=None)
assertIsNot(first, second, msg=None)
assertIsNone(expr, msg=None)
assertIsNotNone(expr, msg=None)
assertIn(first, second, msg=None)
assertNotIn(first, second, msg=None)
assertIsInstance(obj, cls, msg=None)
assertNotIsInstance(obj, cls, msg=None)
assertGreater(first, second, msg=None)
assertGreaterEqual(first, second, msg=None)
assertLess(first, second, msg=None)
assertLessEqual(first, second, msg=None)