断言即进行预期结果和实际结果比对
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
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
assertGreater(a, b) a > b
assertGreaterEqual(a, b) a >= b
注:可以在断言最后一个参数中加入自定义的测试失败信息,如: assertEqual(10, 20, ”10!=20测试失败”) 当断言失败时,显示该消息
代码示例:
# 常用断言 import unittest class assert_class(unittest.TestCase): def setUp(self): print("我是setUp方法,进行测试前的初始化工作") def tearDown(self) -> None: # 表示该方法没有返回值 print("我是tearDown方法,执行测试后的清除工作") def test_case(self): # self.assertEqual(2,3,"2!=3,断言失败") # 判断2!=3 ,断言失败 self.assertEqual(2,2) # 判断2==2 self.assertNotEqual(4,5) # 判断 4!=5 self.assertIn(2,[1,2,3]) # 判断 2 in [1,2,3] self.assertNotIn(4,[1,2,3]) # 判断 4 not in [1,2,3] self.assertTrue("a") # 判断 a is True self.assertFalse(False) # 判断 False is False self.assertIs(3,3) # 判断 3 is 3 self.assertIsNot(3,4) # 判断 3 is not 4 self.assertIsNone(None) # 判断 None is None self.assertIsNotNone("d") # 判断 c is not None if __name__ == '__main__': unittest.main()