当我们在使用 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 地址:
然后,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
当相同入参和断言结果的用例越多,这种写法用起来越爽!
来源: http://www.cnblogs.com/fnng/p/6580636.html