Python unittest:setUpClass使用非静态方法

时间:2013-03-25 10:26:47

标签: python unit-testing

我是Python的初学者并开始在Python中设计单元测试,我需要在运行测试类之前将一些消息发布到服务器(因为它会搜索它们)。因此,我需要调用非静态方法postMessages()

我得到的错误的堆栈跟踪是这个 -

    Error
Traceback (most recent call last):
  File ".../TestMsgs.py", line 23, in setUpClass
    instance = cls()
  File ".../python2.7/unittest/case.py", line 191, in __init__
    (self.__class__, methodName))
ValueError: no such test method in <class 'TestMsgs.TestMsgs'>: runTest

我在代码中有这样的东西:

class A(object):

    def postMessages(self):
        print "i post messages in the server!"

class B(A):

    @classmethod
    def setUpClass(cls):
        cls.foo()  # should post messages for the tests in the class to work on

现在没有选择让foo保持静态。如何在postMessages()中实例化B(或A,就此而言),以便我可以在setUpClass()中使用它?

1 个答案:

答案 0 :(得分:3)

在阅读了TestCase的__init__方法后,我发现您需要为其提供测试方法名称。默认值为“runTest”,这就是弹出错误的原因。

import unittest 

class A(unittest.TestCase):

    def postMessages(self):
        print "i post messages in the server!"

class B(A):

    @classmethod
    def setUpClass(cls):
        cls.foo(cls(methodName='test_method')) # should post messages for the tests in the class to work on

    def foo(self):
        self.postMessages()

    def test_method(self):
        pass


B.setUpClass()

您可以看到它在interactive Python console here中运行。它将打印出“我在服务器中发布消息!”

您需要在班级中传递有效方法名称的原因可以在source code for unittest中清楚地看到:

class TestCase: 
    """A class whose instances are single test cases.""" 

    def __init__(self, methodName='runTest'): 
        """Create an instance of the class that will use the named test 
           method when executed. Raises a ValueError if the instance does 
           not have a method with the specified name. 
        """ 
        try: 
           self._testMethodName = methodName 
           testMethod = getattr(self, methodName) 
           self._testMethodDoc = testMethod.__doc__ 
           except AttributeError: 
               raise ValueError, "no such test method in %s: %s" % \ 
                   (self.__class__, methodName) 

如果您想将参数传递给刚刚传入的方法,那么您需要执行类似

的操作
class A(unittest.TestCase):

    def foo(self, arg1):
        pass

a = A(methodName='foo')
a.foo('an_argument')

但这整个问题确实是错误的。您应该重构而不是使用静态方法调用实例方法。这太傻了。