unittest框架的TestCase类提供以下方法用于测试结果的判断
方法 | 检查 | 版本 |
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 | 3.1 |
assertIsNot(a, b) | a is not b | 3.1 |
assertIsNone(x) | x is None | 3.1 |
assertIsNotNone(x) | x is not None | 3.1 |
assertIn(a, b) | a in b | 3.1 |
assertNotIn(a, b) | a not in b | 3.1 |
assertIsInstance(a, b) | isinstance(a,b) | 3.1 |
assertNotIsInstance(a, b) | not isinstance(a,b) | 3.1 |
-assertEqual(first,second,msg=None)
断言第一个参数和第二个参数是否相等,如果不相等则测试失败
-assertNotEqual(first,second,msg=None)
assertNotEqueal()和assertEqual()相反,它用于第一个参数与第二个参数是否不相等,如果相等则测试失败
-assertTrue(expr,msg=None)
-assertFalse(expr,msg=None)
测试表达式是true(或false)
-assertIn(first,second,msg=None)
-assertNotIn(first,second,msg=None)
判断第一个参数是否在第二个参数中,反过来讲,第二个参数是否包含第一个参数
-assertIs(first,second,msg=None)
-assertIsNot(first,second,msg=None)
断言第一个参数和第二个参数是否为同一个对象
-assertIsNone(first,second,msg=None)
-assertIsNotNone(first,second,msg=None)
断言表达式是否为None对象
-assertIsInstance(first,second,msg=None)
-assertIsNotInstance(first,second,msg=None)
断言obj是否为cls的一个实例
unittest案例:
calculate.py:
class Math:
def __init__(self,a,b):
self.a = int(a)
self.b = int(b) def add(self):
return self.a + self.b
test_Math.py:
from calculator import Math
import unittest class TestMath(unittest.TestCase): def setUp(self):
print("test start") def test_add(self):
j = Math(5,10)
self.assertEquals(j.add(),15)
# self.assertEquals(j.add(),12) def test_add1(self):
j = Math(55,100)
self.assertNotEqual(j.add(),145) def test_add2(self):
j = Math(5,10)
self.assertTrue(j.add() > 10) def assertIs_test(self):
self.assertIs("abc","abc")
# self.assertIs("ab","abc") def assertIn_test(self):
self.assertIn("python","hello python")
# self.assertIn("abc","hello python") def tearDown(self):
print("test end") if __name__ == '__main__':
# unittest.main()
# 构造测试集
suit = unittest.TestSuite()
suit.addTest(TestMath("test_case"))
# 执行测试
runner = unittest.TextTestRunner()
runner.run(suit)