实例:
#被测对象 a.py |
|
def add(a,b): |
|
return a+b |
|
#测试类 Test.py |
|
import unittest |
|
from common.a import add |
|
class Test(unittest.TestCase): |
|
def setUp(self): #重写父类setUp的方法,用于执行用例之前的准备工作。 |
|
print("setUp") |
|
#pass |
|
def tearDown(self): ##重写父类的tearDown的方法。用于执行用例之后的扫尾工作。 |
|
print("tearDown") |
|
#pass |
|
#测试用例方法用于测试add的函数,这个方法必须以test开头 |
|
def test_int_add(self): |
|
print("test_int_add") |
|
sum = add(10,20) |
|
#断言结果 |
|
self.assertEqual(sum,30) |
|
def test_float_add(self): |
|
print("test_float_add") |
|
sum = add(10.2,20.8) |
|
#断言结果 |
|
self.assertEqual(sum,31) |
|
if __name__ == '__main__': |
|
unittest.main() |
常用的assert语句
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
assertNotIsInstance(a,b) not isinstance(a,b)
assertGreater(a,b) a>b
assertGreaterEqual(a,b) a>=b
assertLess(a,b) a<b
assertLessEqual(a,b) a<=b
unittest创建测试代码的方式:
#方式一:创建子类继承unittest.TestCase,然后重写runTest方法 |
|
class WidgetTestCase(unittest.TestCase): |
|
def setUp(self): |
|
pass |
|
def runTest(self): |
|
pass |
|
def tearDown(self): |
|
pass |
|
#方式二:编写以test开头的方法 |
|
class WidgetTestCase(unittest.TestCase): |
|
def setUp(self): |
|
pass |
|
def test_xx1(self) |
|
def test_xx2(self) |
|
... |
|
def test_xxN(self) |
|
def tearDown(self): |
|
pass |
unittest构建测试套件(测试用例集合):
前提Tester是继承了unittest.TestCase的子类
#方式一: |
|
</ |