应用程序上运行单元测试

应用程序上运行单元测试

本文介绍了如何在 Tkinter 应用程序上运行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习TDD,我正在开发一个程序使用 Tkinter GUI.唯一的问题是一旦调用了 .mainloop() 方法,测试套件就会挂起,直到窗口关闭.

I've just begun learning about TDD, and I'm developing a program using a Tkinter GUI. The only problem is that once the .mainloop() method is called, the test suite hangs until the window is closed.

这是我的代码示例:

# server.py
import Tkinter as tk

class Server(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.mainloop()
# test.py
import unittest
import server

class ServerTestCase(unittest.TestCase):
    def testClassSetup(self):
       server.Server()
       # and of course I can't call any server.whatever functions here

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

测试 Tkinter 应用程序的合适方法是什么?还是只是不"?

What is the appropriate way of testing Tkinter apps? Or is it just 'dont'?

推荐答案

您可以做的一件事是在单独的线程中生成主循环并使用您的主线程运行实际测试;按原样观看主循环线程.确保在执行断言之前检查 Tk 窗口的状态.

One thing you can do is spawn the mainloop in a separate thread and use your main thread to run the actual tests; watch the mainloop thread as it were. Make sure you check the state of the Tk window before doing your asserts.

多线程任何代码都很难.您可能希望将 Tk 程序分解为可测试的部分,而不是一次对整个程序进行单元测试(这实际上不是单元测试).

Multithreading any code is hard. You may want to break your Tk program down into testable pieces instead of unit testing the entire thing at once (which really isn't unit testing).

我最终建议至少在控制级别进行测试,如果您的程序不是更低的话,它将极大地帮助您.

I would finally suggest testing at least at the control level if not lower for your program, it will help you tremendously.

这篇关于如何在 Tkinter 应用程序上运行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:29