如何对python中复杂的class中的方法进行单元测试?

How to make unit tests for a methods in complicated class in python?

我想为 filename_to_txt 方法创建单元测试:

class some_panel(wx.Panel):
    def __init__(self,parent,Some_class,some_handler,Some_Event):
        wx.Panel.__init__(self,parent=parent)
        self.parent = parent
        self.some_handler = some_handler
        self.some_Event = Some_Event
        self.some_another_class = Some_class

    def filename_to_txt(self,input_filename):
        splitted = input_filename.split(".raw")
        txt_filename  = splitted[0] + splitted[1] + ".txt"
        return txt_filename

我应该如何为该方法编写单元测试?

它在某些 class 中是静态方法,但要测试它,首先我必须创建 Some_panel class.

的实例

我真的必须为 Some_panel class 的 __init__ 方法提供所有参数吗?有没有另一种更好的方法,为此我不必创建 Some_panel class 的实例来测试 filename_to_txt 方法。

import unittest
from some_file import Some_panel

class TestSomething(unittest.TestCase):
    def testname(self):
        some_panel = Some_panel( ???? )
        testfilename = "TestFilename.raw.001"
        result = some_panel.filename_to_txt(input_filename = testfilename)
        self.assertEqual(result, "TestFilename.001.txt", "Something is wrong")

如果是静态方法,去掉self参数,用@staticmethod装饰器装饰。然后,您可以使用 some_panel.filename_to_text(filename).

将其作为纯函数调用

我认为最好的方法是去掉 SomePanel class。

class SomePanelStub(SomePanel):
  def __init__(self):
    self.parent = None
    self.some_handler = None
    self.some_Event = None
    self.some_another_class = None

现在在你的单元测试中 Class

def SetUp(self):
  self.helper = SomePanelStub()

现在您已经删除了 SomePanel 并且可以轻松模拟任何依赖项。