python里如何测试
在Python中,我们可以使用unittest模块来编写和运行测试用例,以下是一个简单的示例:

1、我们需要导入unittest模块,并创建一个继承自unittest.TestCase的测试类,在这个类中,我们可以定义多个以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'])
# 检查空格分隔符是否起作用
with self.assertRaises(TypeError):
s.split(2)
2、我们需要在命令行中运行这个测试脚本,我们可以使用unittest模块的TestLoader类来加载测试用例,然后使用TextTestRunner类来运行它们。
python m unittest test_string_methods.py
3、如果所有的测试用例都通过了,那么你会看到类似以下的输出:
. Ran 3 tests in 0.001s OK
4、如果某个测试用例失败了,那么你会看到类似以下的输出:
F
FAIL: test_upper (__main__.TestStringMethods)
Traceback (most recent call last):
File "test_string_methods.py", line 6, in test_upper
self.assertEqual('foo'.upper(), 'FOO')
AssertionError: 'FOO' != 'foo'
Ran 3 tests in 0.001s
FAILED (failures=1)
这就是在Python中编写和运行测试用例的基本方法。
分享文章:python里如何测试
本文来源:http://www.jxjierui.cn/article/dpjjijp.html


咨询
建站咨询
