Python unittest單元測試框架實現(xiàn)參數(shù)化
當我們在使用TestNG時,發(fā)現(xiàn)它有一個非常好用的參數(shù)化功能。當你的測試用例有固定的參數(shù)和斷言結果時,它可以相似用例的節(jié)省用例的個數(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 { // 定義測試數(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); } }
相對而言,Python下面單元測試框架要弱上少,尤其是Python自帶的unittest測試框架,不支持參數(shù)化,不支持多線程執(zhí)行用例,不支持HTML測試報告的生成...。好再,部分不足我們可以通過unittest擴展來滿足需求。比如現(xiàn)在要介紹一個參數(shù)化的擴展。
在沒有參數(shù)化功能的情況下,我們的用例需要這樣編寫。
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單元測試框架實現(xiàn)參數(shù)化的擴展。同時支持不同的單元測試框架。
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)
執(zhí)行結果:
test_add_0_01 (__main__.TestAdd) ... ok
test_add_1_02 (__main__.TestAdd) ... FAIL
test_add_2_03 (__main__.TestAdd) ... ok
當相同入?yún)⒑蛿嘌越Y果的用例越多,這種寫法用起來越爽!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python爬蟲 線程池創(chuàng)建并獲取文件代碼實例
這篇文章主要介紹了python爬蟲 線程池創(chuàng)建并獲取文件代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09python利用elaphe制作二維條形碼實現(xiàn)代碼
條形碼的應用將會越來越廣泛,看到了一篇文章,寫的挺好的!用手機拍二維碼,查二維碼確實很爽!這將成為一種潮流2012-05-05Python 比較文本相似性的方法(difflib,Levenshtein)
今天小編就為大家分享一篇Python 比較文本相似性的方法(difflib,Levenshtein),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10selenium獲取元素定位的方法總結(動態(tài)獲取元素)
要想操作一個元素,首先應該識別這個元素,人有各種的特征(屬性),可以通過其特征找到人,同理,界面的某個元素會有各種的特征(屬性),可以通過這個屬性找到這對象,本文給大家介紹了python?selenium獲取元素定位的8種方法,需要的朋友可以參考下2024-02-02