2014-09-21 38 views
1

如果我有兩個應該做同樣的事情的函數的實現,有什麼辦法測試兩個函數針對相同的測試用例嗎?對多個實現運行相同的測試

正如我有:

def foo1(args): 
    // do some stuff 
    return result1 

def foo2(args): 
    // do some other stuff 
    return result2 

import unittest 

class TestFoo(unittest.TestCase): 

    def test_1(self): 
     arg = // something 
     result = // expected result 
     self.failUnless(foo1(arg) == result) 

    def test_2(self): 
     arg = // something 
     result = // expected result 
     self.failUnless(foo2(arg) == result) 

但是test_2相同TEST_1,除了被測試的功能。如果我對測試用例進行了更改,則必須更改兩者,如果我添加了更多測試,則必須將其複製。

我可以這樣做:

class TestFoo(unittest.TestCase): 
    def test_(self): 
     fns = [foo1, foo2] 
     arg = // something 
     result = // expected result 
     for fn in fns: 
      self.failUnless(fn(arg) == result) 

這有更少的代碼重複,但現在如果任一執行失敗的測試,單元測試不報告哪一個。

是否可以通過要測試的函數對TestCase進行參數化?

我知道我不應該試圖在測試中過於聰明,所以也許我應該保持原樣,重複代碼和所有內容。

回答

1

以下是usnig類屬性和繼承的一種方法。

def foo1(a, b): 
    return b + a 

def foo2(a, b): 
    return a + b 

import unittest 

class TestFooBase: 
    def test_1(self): 
     self.assertEqual(self.impl(0, 0), 0) 
    def test_2(self): 
     self.assertEqual(self.impl(1, 2), 3) 

class TestFoo1(unittest.TestCase, TestFooBase): 
    impl = staticmethod(foo1) 

    # OR 
    # def impl(self, *args, **kwargs): 
    # return foo1(*args,**kwargs) 


class TestFoo2(unittest.TestCase, TestFooBase): 
    impl = staticmethod(foo2) 

注意TestFooBase不應該是unittest.TestCase一個子類。否則將運行6次(3x2)測試而不是4次(2次2次)。

TestFooBase並非嚴格必要,如果您使TestFoo1繼承TestFoo2(反之亦然)。

class TestFoo1(unittest.TestCase): 
    impl = staticmethod(foo1) 
    def test_1(self): 
     self.assertEqual(self.impl(0, 0), 0) 
    def test_2(self): 
     self.assertEqual(self.impl(1, 2), 3) 

class TestFoo2(TestFoo1): 
    impl = staticmethod(foo2) 

順便說一句,failUnless已棄用。如上面的代碼所示,使用assertTrueassertEqual

相關問題