Python unittest單元測(cè)試框架實(shí)現(xiàn)參數(shù)化
當(dāng)我們?cè)谑褂肨estNG時(shí),發(fā)現(xiàn)它有一個(gè)非常好用的參數(shù)化功能。當(dāng)你的測(cè)試用例有固定的參數(shù)和斷言結(jié)果時(shí),它可以相似用例的節(jié)省用例的個(gè)數(shù)。
例子如下:
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 { // 定義測(cè)試數(shù)據(jù) @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); }}
相對(duì)而言,Python下面單元測(cè)試框架要弱上少,尤其是Python自帶的unittest測(cè)試框架,不支持參數(shù)化,不支持多線程執(zhí)行用例,不支持HTML測(cè)試報(bào)告的生成...。好再,部分不足我們可以通過(guò)unittest擴(kuò)展來(lái)滿足需求。比如現(xiàn)在要介紹一個(gè)參數(shù)化的擴(kuò)展。
在沒(méi)有參數(shù)化功能的情況下,我們的用例需要這樣編寫。
import unittestclass 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是一個(gè)針對(duì)Python單元測(cè)試框架實(shí)現(xiàn)參數(shù)化的擴(kuò)展。同時(shí)支持不同的單元測(cè)試框架。
GitHub地址:https://github.com/wolever/nose-parameterized
然后,unittest就可以像TestNG一樣寫用例了。
import unittestfrom nose_parameterized import parameterizedclass 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)
執(zhí)行結(jié)果:
test_add_0_01 (__main__.TestAdd) ... ok
test_add_1_02 (__main__.TestAdd) ... FAIL
test_add_2_03 (__main__.TestAdd) ... ok
當(dāng)相同入?yún)⒑蛿嘌越Y(jié)果的用例越多,這種寫法用起來(lái)越爽!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)感知機(jī)模型的示例2. .net core 中 WebApiClientCore的使用示例代碼3. iOS UIScrollView和控制器返回手勢(shì)沖突解決方法4. springboot多模塊包掃描問(wèn)題的解決方法5. windows下安裝PHP性能分析工具 xhprof 筆記6. 基于Django集成CAS實(shí)現(xiàn)流程詳解7. django中url映射規(guī)則和服務(wù)端響應(yīng)順序的實(shí)現(xiàn)8. Android Studio編寫AIDL文件后如何實(shí)現(xiàn)自動(dòng)編譯生成9. 基于vue實(shí)現(xiàn)探探滑動(dòng)組件功能10. 深入淺出 妙用Javascript中apply、call、bind
