unittest运行测试的三种方式:
- unittest.main()
- TestSuit/TextTestRunner
- discover()/ TextTestRunner
TestSuit/TextTestRunner
灵活测试某些用例
import unittest
class MyTest(unittest.TestCase):
def test_case(self):
print("test 2 + 2 ")
self.assertEqual(2 + 2, 4)
class MyTest2(unittest.TestCase):
def test_case(self):
print("test 2 - 2 ")
self.assertEqual(2 - 2, 0)
if __name__ == '__main__':
# 测试套件
suit = unittest.TestSuite()
suit.addTest(MyTest("test_case"))
suit.addTest(MyTest2("test_case"))
# 运行测试套件
runner = unittest.TextTestRunner()
runner.run(suit)
discover()/ TextTestRunner
import unittest
suit = unittest.defaultTestLoader.discover("./", "unittest_*.py") # 执行所有unittest_开头的文件
# 运行测试套件
runner = unittest.TextTestRunner()
runner.run(suit)
# unittest_assert.py
import unittest
class MyClass(unittest.TestCase):
def test_equal(self):
user = "admin"
self.assertEqual(user, "admin")
self.assertNotEqual("a", "b")
def test_in(self):
info = "恭喜,你的邮件已经发送成功!"
self.assertIn("成功", info)
self.assertNotIn("失败", info)
def test_true(self):
a = False
b = True
self.assertTrue(b)
self.assertFalse(a)
if __name__ == '__main__':
unittest.main()
# unittest_demo.py
import unittest
class MyClass(unittest.TestCase):
def test_equal(self):
user = "admin"
self.assertEqual(user, "admin")
self.assertNotEqual("a", "b")
def test_in(self):
info = "恭喜,你的邮件已经发送成功!"
self.assertIn("成功", info)
self.assertNotIn("失败", info)
def test_true(self):
a = False
b = True
self.assertTrue(b)
self.assertFalse(a)
if __name__ == '__main__':
unittest.main()
# unittest_fixture.py
import unittest
def setUpModule():
print(">>>>>>>>>>>>>> start module")
def tearDownModule():
print(">>>>>>>>>>>>>> start module")
class MyClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("====> start class")
@classmethod
def tearDownClass(cls):
print("===> end class")
def setUp(self):
print("start test")
def tearDown(self):
print("end test")
def test_case(self):
print("---->test case")
self.assertEqual(2+2, 4)
def test_case2(self):
print("---->test case2")
self.assertEqual(3, 4)
class MyClass2(unittest.TestCase):
def test_case3(self):
print("---> test case3")
self.assertEqual(3, 3)
if __name__ == '__main__':
unittest.main()
# unittest_runner.py
import unittest
class MyTest(unittest.TestCase):
def test_case(self):
print("test 2 + 2 ")
self.assertEqual(2 + 2, 4)
class MyTest2(unittest.TestCase):
def test_case(self):
print("test 2 - 2 ")
self.assertEqual(2 - 2, 1)
if __name__ == '__main__':
# unittest.main()
# 测试套件
suit = unittest.TestSuite()
# suit.addTest(MyTest2("test_case"))
suit.addTest(MyTest("test_case"))
# 运行测试套件
runner = unittest.TextTestRunner()
runner.run(suit)