2014-09-21 47 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

相关问题