2014-02-24 45 views
8

列表相同的測試我有這個測試單元測試 - 運行輸入和輸出

import unittest 

class TestName(unittest.TestCase): 

     def setUp(self): 
       self.name = "Bob" 
       self.expected_name = "Bob" 


     def test_name(self): 
       # ... some operation over self.name 
       print self.name 
       self.assertEquals(self.name, self.expected_name) 

if __name__ == '__main__': 
     unittest.main(verbosity=2) 

我怎麼能運行的測試實例?

運行的輸入和輸出(["Bob", "Alice", ...])列表相同的測試,也許像

TestName(name="Bob", expected_name="Bob") 
TestName(name="Alice", expected_name="Alice") 
+1

僅供參考,看一看[滴滴涕(https://github.com/txels/ddt)封裝。 – alecxe

+0

python-testscenarios –

回答

15

結賬DDT (Data-Driven/Decorated Tests)

DDT允許您通過將測試用例與不同的測試數據一起運行,使其顯示爲多個測試用例。

考慮該例子中,使用DDT:

import unittest 

from ddt import ddt, data, unpack 


@ddt 
class TestName(unittest.TestCase): 

     # simple decorator usage: 
     @data(1, 2) 
     def test_greater_than_zero(self, value): 
      self.assertGreater(value, 0) 

     # passing data in tuples to achieve the 
     # scenarios from your given example: 
     @data(('Bob', 'Bob'), ('Alice', 'Alice')) 
     @unpack 
     def test_name(self, first_value, second_value): 
      name, expected_name = first_value, second_value 
      self.assertEquals(name, expected_name) 

if __name__ == '__main__': 
     unittest.main(verbosity=2) 

我定義2種的測試方法在上述代碼中,但4測試用例將運行,使用我在裝飾提供的數據。

輸出:

test_greater_than_zero_1 (__main__.TestName) ... ok 
test_greater_than_zero_2 (__main__.TestName) ... ok 
test_name_('Alice', 'Alice') (__main__.TestName) ... ok 
test_name_('Bob', 'Bob') (__main__.TestName) ... ok 

---------------------------------------------------------------------- 
Ran 4 tests in 0.000s 

OK 
2

我會用一個混合或在此元類,作爲單元測試查找類,而不是實例。

class TestMixin (object): 
    def test_name(): 
     print self.name 

class TestName (unittest.TestCase, TestMixin): 
    ... 
+0

mixin適用於我的應用程序。 – Onlyjus