新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python里如何測試
在Python中,我們可以使用unittest模塊來編寫和運行測試用例,以下是一個簡單的示例:

1、我們需要導(dǎo)入unittest模塊,并創(chuàng)建一個繼承自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中編寫和運行測試用例的基本方法。
標(biāo)題名稱:python里如何測試
網(wǎng)頁網(wǎng)址:http://www.dlmjj.cn/article/dpjjijp.html


咨詢
建站咨詢
