繁体   English   中英

Python unittest:setUpClass使用非静态方法

[英]Python unittest : setUpClass uses a non-static method

我是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()中使用它?

__init__阅读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()

您可以在此处看到它在交互式Python控制台中运行。 它将打印出“我在服务器中发布消息!”

您需要在类中传递有效方法名称的原因可以在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')

但是,整个问题确实感觉很不对。 您应该重构而不是让静态方法调用实例方法。 真傻。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM