在 Python 中,可以使用 unittest 模块来编写单元测试。
下面我来简单介绍一下如何使用 unittest。
编写测试用例
首先,我们需要编写测试用例。测试用例是一个类,其中包含多个测试方法,每个测试方法用来测试一个功能是否正常。
测试方法必须以 test 开头。
下面是一个简单的测试用例示例:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
在上面的示例中,我们创建了一个名为 TestStringMethods 的测试用例类,其中包含三个测试方法 test_upper、test_isupper 和 t