Python单元测试初始值

时间:2013-01-13 23:23:38

标签: python unit-testing

很抱歉,如果这个问题很愚蠢。我创建了一个unittest类,需要从外部获取给定的输入和输出。因此,我想应该启动这些值。但是,我在以下代码中遇到了一些错误:

CODE:

import unittest
from StringIO import StringIO

##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
    return a+b

class MyTestCase(unittest.TestCase):
    def __init__(self,a,b,out):
        self.a=a
        self.b=b
        self.out=out
    def testMsed(self):
        for i in range(self.tot_iter):
            print i
            fun = func1(self.a[i],self.b[i])
            value = self.out[i]
            testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
            self.assertEqual(round(fun,3),round(value,3),testFailureMessage)

if __name__ == '__main__':
    f = MyTestCase(a,b,out)

from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun

然而,我收到以下错误

Traceback (most recent call last):
  File "C:testing.py", line 33, in <module>
    result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
  File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
    return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
    if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class

有人能给我一些建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

问题的根源是这一行,

result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))

unittest.makeSuite需要,而不是类的实例。所以只是MyTestCase,而不是MyTestCase(a,b,out)。这意味着您无法以您尝试的方式将参数传递给测试用例。您应该将代码从 init 移动到setUp函数。在setUp中访问a,b和out作为全局变量,或者查看this link以获取有关将参数传递给单元测试的信息。

顺便说一句,here是python中发生问题的源文件。可能需要阅读信息。