单元测试可以帮助我们准确迅速地定位出现问题的模块和单元。
单元测试的对象是函数,必须有输出结果(哪怕是异常输出),以便单元测试模块能够捕获返回值,并且与预期值进行比较,从而得出测试通过与否
单元测试的加载可以通过unittest.main()来启动单元测试的测试模块。
而testsuit里存放的就是单元测试的用例,下面分别列出了2种方法的使用。
- setUp(): 每个测试函数运行前运行
- tearDown(): 每个测试函数运行完后执行
- setUpClass(): 必须使用@classmethod 装饰器,所有test运行前运行一次
- tearDownClass(): 必须使用@classmethod装饰器,所有test运行完后运行一次
例1:测试函数
def sum(x, y): return x + y def sub(x, y): return x - y
单元测试模块
class mytest(unittest.TestCase): #所有执行测试的类都继承TestCase类 #初始化工作 def setUp(self): pass #清退工作 def tearDown(self): pass #具体的测试用例,一定要以test开头 def testsum_1(self): self.assertEqual(sum(1, 2), 3, "test sum fail") def testsum_2(self): self.assertEqual(sum(1, 2), 2, "test sum fail") def testsub(self): self.assertEqual(sub(2, 1), 1, "test sub fail") if __name__ == "__main__": unittest.main()
测试结果
..F ====================================================================== FAIL: testsum_2 (__main__.mytest) ---------------------------------------------------------------------- Traceback (most recent call last): File "E:/task/???????/test1.py", line 18, in testsum_2 self.assertEqual(sum(1, 2), 2, "test sum fail") AssertionError: test sum fail ---------------------------------------------------------------------- Ran 3 tests in 0.003s FAILED (failures=1)
注:F表示fail, F前的点表示测试通过,有E的话表示程序自身异常
例2:测试类
class myclass: def __init__(self): pass def sum(self, x, y): return x + y def sub(self, x, y): return x - y
测试代码
class mytest(unittest.TestCase): def setUp(self): self.tclass = myclass() def tearDown(self): pass def testsum_1(self): self.assertEqual(self.tclass.sum(1, 2), 3, "test sum fail") def testsum_2(self): self.assertEqual(self.tclass.sum(1, 2), 3, "test sum fail") def testsub(self): self.assertEqual(self.tclass.sub(2, 1), 1, "test sub fail") if __name__ == "__main__": unittest.main()
结果
..F ====================================================================== FAIL: testsum_2 (__main__.mytest) ---------------------------------------------------------------------- Traceback (most recent call last): File "E:/task/???????/test2.py", line 24, in testsum_2 self.assertEqual(self.tclass.sum(1, 2), 5, "test sum fail") AssertionError: test sum fail ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1)
例3:构造测试集
被测代码
class myclass: def __init__(self): pass def sum(self, x, y): return x + y def sub(self, x, y): return x - y
测试代码
class mytest(unittest.TestCase): def setUp(self): self.tclass = myclass() def tearDown(self): pass def testsum_1(self): self.assertEqual(self.tclass.sum(1, 2), 3, "test sum fail") def testsum_2(self): self.assertEqual(self.tclass.sum(1, 2), 5, "test sum fail") def testsub(self): self.assertEqual(self.tclass.sub(2, 1), 1, "test sub fail") def suite(): suite = unittest.TestSuite() suite.addTest(mytest("testsum_1")) suite.addTest(mytest("testsum_2")) suite.addTest(mytest("testsub")) return suite if __name__ == "__main__": unittest.main(defaultTest = "suite")
时间: 2024-10-29 08:54:43