這篇文章主要為大家展示了Python unittest單元測試框架如何實現參數化,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
當我們在使用TestNG時,發現它有一個非常好用的參數化功能。當你的測試用例有固定的參數和斷言結果時,它可以相似用例的節省用例的個數。
例子如下:
import static org.testng.Assert.assertEquals;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Created by fnngj on 2017/3/19.
*/
public class Demo {
// 定義測試數據
@DataProvider(name = "data")
public Object[][] Users() {
return new Object[][] {
{ 1, 1, 2},
{ 2, 2, 5},
{ 3, 3, 6},
};
}
@Test(dataProvider="data")
public void testAdd(int a,int b,int c) {
assertEquals(a + b, c);
}
}相對而言,Python下面單元測試框架要弱上少,尤其是Python自帶的unittest測試框架,不支持參數化,不支持多線程執行用例,不支持HTML測試報告的生成...。好再,部分不足我們可以通過unittest擴展來滿足需求。比如現在要介紹一個參數化的擴展。
在沒有參數化功能的情況下,我們的用例需要這樣編寫。
import unittest
class TestAdd(unittest.TestCase):
def test_add_01(self):
self.assertEqual(1 + 2, 3)
def test_add_02(self):
self.assertEqual(2 + 2, 5)
def test_add_03(self):
self.assertEqual(3 + 3, 6)
if __name__ == '__main__':
unittest.main()nose-parameterized是一個針對Python單元測試框架實現參數化的擴展。同時支持不同的單元測試框架。

GitHub地址:https://github.com/wolever/nose-parameterized
然后,unittest就可以像TestNG一樣寫用例了。
import unittest
from nose_parameterized import parameterized
class TestAdd(unittest.TestCase):
@parameterized.expand([
("01",1, 1, 2),
("02",2, 2, 5),
("03",3, 3, 6),
])
def test_add(self, name, a, b, c):
self.assertEqual(a + b, c)
if __name__ == '__main__':
unittest.main(verbosity=2)執行結果:
test_add_0_01 (__main__.TestAdd) ... ok
test_add_1_02 (__main__.TestAdd) ... FAIL
test_add_2_03 (__main__.TestAdd) ... ok
當相同入參和斷言結果的用例越多,這種寫法用起來越爽!
以上就是關于Python unittest單元測試框架如何實現參數化的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。