pythonunittest:setUpClass使用非静态方法

2024-10-04 01:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

我在密码里有这样的东西:

^{pr2}$

现在没有办法让foo成为静态的。如何在postMessages()中实例化B(或A),以便在setUpClass()中使用它?在


Tags: inpy消息堆栈错误lineerror单元测试
1条回答
网友
1楼 · 发布于 2024-10-04 01:30:29

在通读了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中清楚地看到:

^{pr2}$

如果您想将参数传入刚刚传入的方法,则需要执行以下操作

class A(unittest.TestCase):

    def foo(self, arg1):
        pass

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

但这个问题让人觉得很不对。您应该重构,而不是让静态方法调用实例方法。太傻了。在

相关问题 更多 >