Unittest断言

简介

自动化脚本最重要的是断言,正确设置断言以后才能帮助我们判断测试用例执行结果。

断言方法

  • 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)

实践案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import unittest
from calculator import *

class TestMath(unittest.TestCase):
def setUp(self):
print("test is start")

def add_test(self):
j = Math(5,10)
self.assertEqual(j.add(),10)

def add_test1(self):
j = Math(5,10)
self.assertNotEqual(j.add(),10)

def add_test2(self):
j = Math(5,10)
self.assertTrue(j.add()>10)

def assertIs_test(self):
self.assertIs("51zxw",'51zxw')
# self.assertIs("51zxw",'abc')

def assertIn_test(self):
self.assertIn("51zxw","hello,51zxw")
self.assertIn("888","hello,51zxw")

def tearDown(self):
print("Test end")

if __name__=='__main__':

suite=unittest.TestSuite()
suite.addTest(TestMath("assertIn_test"))

runer=unittest.TextTestRunner()
runer.run(suite)