簡體   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