快速上手
# 被测代码
def add_func(a, b):
return a + b
# 测试代码
import unittest
class MyTest(unittest.TestCase):
def test_add_func(self):
# 使用assertEqual判断返回值是否相等
self.assertEqual(add_func(1, 2), 3)
if __name__ == '__main__':
unittest.main()
assert断言方法
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIs(a, b)
assertIsNot(a, b)
assertIsNone(x)
assertIsNotNone(x)
assertIn(a, b)
assertNotIn(a, b)
assertIsInstance(a, b)
assertNotIsInstance(a, b)
组织测试代码
setUp()和 tearDown()
class MyTest(unittest.TestCase):
def setUp(self) -> None:
print("在每个测试方法执行前被调用,预制测试条件")
def tearDown(self) -> None:
print("每个测试方法执行后被调用,恢复测试前的状态")
def test_add_func1(self):
self.assertEqual(add_func(1, 2), 3)
print("test test_add_func1")
def test_add_func2(self):
self.assertEqual(add_func(1, -1), 0)
print("test test_add_func2")
setUpClass 和 tearDownClass
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
print("测试类开始前执行")
return super().setUpClass()
@classmethod
def tearDownClass(cls) -> None:
print("测试类结束后执行")
return super().tearDownClass()
def setUp(self) -> None:
print("在每个测试方法执行前被调用,预制测试条件")
def tearDown(self) -> None:
print("每个测试方法执行后被调用,恢复测试前的状态")
def test_add_func1(self):
self.assertEqual(add_func(1, 2), 3)
print("test test_add_func1")
def test_add_func2(self):
self.assertEqual(add_func(1, -1), 0)
print("test test_add_func2")
参考教程 https://docs.python.org/3.9/library/unittest.html
标签:python,unittest,单元测试,print,add,test,self,def From: https://www.cnblogs.com/rustling/p/17232574.html