判断用例的执行结果
# 断言方法
方法 | 说明 |
---|---|
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 is not in b |
assertIsInstance(a, b) | is instance(a, b) |
assertNotIsInstance(a, b) | not is instance(a,b) |
# 代码示例
class Math: | |
def __init__(self, a, b): | |
self.a = a | |
self.b = b | |
def add(self): | |
return self.a + self.b |
from calculator import Math | |
import unittest | |
class TestMath(unittest.TestCase): | |
def SetUp(self): | |
print("Start test") | |
def test_add(self): | |
j = Math(5, 10) | |
self.assertEqual(j.add(), 15) | |
# 用例失败场景 | |
# self.assertEqual(j.add(), 12) | |
def test_add1(self): | |
j = Math(5, 10) | |
# 断言是否不相等 | |
self.assertNotEqual(j.add(), 12) | |
def assertTrue_test(self): | |
j = Math(5, 10) | |
# 断言是否为真 | |
self.assertTrue(j.add() > 10) | |
def assertIn_test(self): | |
# 断言前者是否包含在后者之中 | |
self.assertIn("test", "assertIn test") | |
def assertIs_test(self): | |
# 断言前者是否为后者 | |
self.assertIs("test", "test") | |
def tearDown(self): | |
print("test end.") | |
if __name__=="__main__": | |
# 构造测试集 | |
suite = unittest.TestSuite() | |
suite.addTest(TestMath("assertIs_test")) | |
# 执行测试 | |
runner = unittest.TextTestRunner() | |
runner.run(suite) |