Python的`unittest`模块是Python标准库中自带的,因此不需要额外安装。您可以直接在Python脚本中导入`unittest`模块并使用它来编写和执行单元测试。
import unittestclass 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'])如果测试失败,将输出此行作为错误消息with self.assertRaises(TypeError):s.split(2)if __name__ == '__main__':unittest.main()
将上述代码保存为文件,例如`test_example.py`,然后在命令行中运行该文件即可执行测试:
python test_example.py
执行结果将显示测试是否通过。

