You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python类中无入参的函数编写测试用例

为CreateVideoList类的add_video_to_playlist方法编写测试用例

我需要为Python类中一个无入参的函数编写测试用例,目标函数是CreateVideoList类下的add_video_to_playlist方法。

目标方法代码

def add_video_to_playlist(self):
        number_to_add = self.input_vide0_add_txt.get()
        video_to_add = lib.get_name(number_to_add)
        play_count = lib.get_play_count(number_to_add)
        if video_to_add is not None:
            self.playlist.append(video_to_add)
            set_text(self.playlist_txt, self.playlist)
            messagebox.showinfo("Play count", print(play_count))
        else:
            set_text(self.playlist_txt, f"Video {number_to_add} not found")

所属类的完整代码

class CreateVideoList():
    def __init__(self, window):
        window.geometry("1000x600")
        window.title("Check Videos")
        window.configure(background= "#333333")

        self.playlist = []

        enter_playlist_name_lbl = Label(window, text="Enter Playlist's name", background="#458B74")
        enter_playlist_name_lbl.grid(row=0, column=0, padx=24, pady=24)

        self.name_txt = Entry(window, width=30)
        self.name_txt.grid(row=0, column=1, padx=24, pady=24)

        create_video_list_btn = Button(window, text="Create Video List", background="#458B74", command=self.create_playlist_clicked)
        create_video_list_btn.grid(row=0, column=2, padx=24, pady=24)

        list_videos_btn = Button(window, text="List All Videos in the library", command=self.list_videos_clicked,  background="#458B74")
        list_videos_btn.grid(row=0, column=3, padx=24, pady=24)

        self.list_txt = tkst.ScrolledText(window, width=48, height=12, wrap="none")
        self.list_txt.grid(row=1, column=0, columnspan=3, sticky="W", padx=9, pady=9)

        enter_video_to_add_lbl = Label(window, text="Enter Video Number to add to new playlist",  background="#458B74")
        enter_video_to_add_lbl.grid(row=2, column=0, padx=24, pady=24)

        self.input_vide0_add_txt = Entry(window, width=7)
        self.input_vide0_add_txt.grid(row=2, column=1, padx=9, pady=9)

        add_button = Button(window, text="Add", background="#458B74", command=self.add_video_to_playlist)
        add_button.grid(row=2, column=2, padx=9, pady=9)

        self.playlist_txt = tkst.ScrolledText(window, width=48, height=12, wrap="none")
        self.playlist_txt.grid(row=1, column=2, columnspan=3, sticky="W", padx=9, pady=9)

        play_button = Button(window, text="Play", background="#458B74")
        play_button.grid(row=2, column=3, padx=9, pady=9)


    def list_videos_clicked(self):
        video_list = lib.list_all()
        set_text(self.list_txt, video_list)


    def create_playlist_clicked(self):
        playlist_name = self.name_txt.get()
        if playlist_name == None:
            raise ValueError("Name cannot be NULL")
        set_text(self.playlist_txt, playlist_name)


    def add_video_to_playlist(self):
        number_to_add = self.input_vide0_add_txt.get()
        video_to_add = lib.get_name(number_to_add)
        play_count = lib.get_play_count(number_to_add)
        if video_to_add is not None:
            self.playlist.append(video_to_add)
            set_text(self.playlist_txt, self.playlist)
            messagebox.showinfo("Play count", print(play_count))
        else:
            set_text(self.playlist_txt, f"Video {number_to_add} not found")


    def play_playlist(self):
        for i in self.playlist.keys():
            lib.increment_play_count(i)
        messagebox.showinfo("Notification", "Playlist is playing")

测试用例实现方案

由于add_video_to_playlist依赖了tkinter组件、外部库lib和messagebox,需要通过Mock隔离这些依赖,确保测试只验证方法本身的逻辑。下面使用unittest结合unittest.mock实现:

测试前置准备

  • 用Mock模拟tkinter窗口对象传入类的构造函数
  • 模拟输入框的get()方法返回测试用的视频编号
  • 模拟lib的get_name和get_play_count方法,根据测试场景返回不同值
  • 模拟set_text函数和messagebox.showinfo方法,验证调用是否符合预期

具体测试用例

import unittest
from unittest.mock import Mock, patch
from your_module import CreateVideoList  # 替换为实际模块名

class TestCreateVideoList(unittest.TestCase):
    def setUp(self):
        # 初始化模拟窗口和类实例
        self.mock_window = Mock()
        self.view = CreateVideoList(self.mock_window)

    @patch('your_module.lib')
    @patch('your_module.set_text')
    @patch('your_module.messagebox')
    def test_add_existing_video_success(self, mock_messagebox, mock_set_text, mock_lib):
        # 配置依赖的Mock返回值
        self.view.input_vide0_add_txt.get = Mock(return_value="1")
        mock_lib.get_name.return_value = "Sample Video"
        mock_lib.get_play_count.return_value = 5

        # 调用目标方法
        self.view.add_video_to_playlist()

        # 验证播放列表更新
        self.assertEqual(self.view.playlist, ["Sample Video"])
        # 验证set_text调用正确
        mock_set_text.assert_called_once_with(self.view.playlist_txt, ["Sample Video"])
        # 验证messagebox被调用
        mock_messagebox.showinfo.assert_called_once()
        # 验证lib方法的参数正确
        mock_lib.get_name.assert_called_once_with("1")
        mock_lib.get_play_count.assert_called_once_with("1")

    @patch('your_module.lib')
    @patch('your_module.set_text')
    @patch('your_module.messagebox')
    def test_add_non_existing_video_show_error(self, mock_messagebox, mock_set_text, mock_lib):
        # 配置依赖的Mock返回值
        self.view.input_vide0_add_txt.get = Mock(return_value="999")
        mock_lib.get_name.return_value = None

        # 调用目标方法
        self.view.add_video_to_playlist()

        # 验证播放列表未修改
        self.assertEqual(self.view.playlist, [])
        # 验证错误提示被设置
        mock_set_text.assert_called_once_with(self.view.playlist_txt, "Video 999 not found")
        # 验证messagebox未被调用
        mock_messagebox.showinfo.assert_not_called()
        # 验证lib方法的参数正确
        mock_lib.get_name.assert_called_once_with("999")

if __name__ == '__main__':
    unittest.main()

注意事项

  • 将代码中的your_module替换为包含CreateVideoList类的实际模块名
  • 确保set_text、lib等外部依赖的patch路径与实际导入路径一致
  • 测试无需启动真实tkinter窗口,通过Mock即可完成逻辑验证

内容的提问来源于stack exchange,提问作者Momoka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:30:56