如何测试使用用户界面的功能

How to test a function that is using user-interface

我正在尝试测试需要用户交互的功能。问题是我怎样才能以编程方式做到这一点?

这是一个示例,我们要求用户 select 列表中的一个项目 (main.py) :

import tkinter as tk
from tkinter import Button, OptionMenu, StringVar


def ask_for_item_in_list(lst, title, default_index=0):

    root, item = tk.Tk(), None
    WIDTH, HEIGHT = 300, 120

    root.title(title)

    root.maxsize(width=WIDTH, height=HEIGHT)
    root.minsize(width=WIDTH, height=HEIGHT)
    root.resizable(0, 0)

    variable = StringVar(root)
    variable.set(lst[default_index])

    option_menu = OptionMenu(root, variable, *lst)
    option_menu.pack(fill="none", expand=True)

    def on_close():
        # The window has been closed by the user
        variable.set(None)
        close()

    def close():
        # It quits mainloop()
        root.quit()
        # It closes the window
        root.destroy()

    button_ok = Button(root, text='OK', command=close)
    button_ok.pack(fill='none', expand=True)

    root.protocol('WM_DELETE_WINDOW', on_close)

    # Execution stops here as long as the user has not closed the window or
    # pressed ok
    root.mainloop()

    # We retrieve the selected item
    item = variable.get()
    if item == 'None':
        item = None

    return item

if __name__ == '__main__':
        lst = ['Item 1', 'Item 2', 'Item 3']
        title = 'Select an item'
        default_selected_idx = lst.index('Item 2')

        selected_item = ask_for_item_in_list(lst, title, default_selected_idx)

        print(selected_item)

我使用 pytest 编写了我所有的测试,因为我不能使用面向对象的编程。实际上,代码必须由非专业开发人员维护。

如您所见,我无法以这种方式测试此功能,因为它将等待用户输入 (test_main.py):

from main import ask_for_item_in_list


def test_ask_for_item_in_list():
    lst = ['Item 1', 'Item 2', 'Item 3']
    title = 'Select an item'

    # Here TRY to test if changing the default selected index works
    default_selected_idx = lst.index('Item 2')

    # Code to simualte that the user as clicked on OK ?
    # user.click_button('OK') ?
    selected_item = ask_for_item_in_list(lst, title, default_selected_idx)

    assert selected_item == 'Item 2'

这个问题我遇到过很多次(无论使用什么语言),我想知道应该如何以一种干净的方式完成。

感谢阅读! :)

通常会预先用期望值或特殊值填充用户输入,然后多次调用测试函数。您也可以使用各种工具模拟点击。

在 C++ 中你可以这样做:

int number_of_tests = 10;
int tests_passed = 0;
tests_passed += my_test_function_int(0);
tests_passed += my_test_function_int(-1);
...
tests_passed += my_test_function_string("foo");
tests_passed += my_test_function_string("");
tests_passed += my_test_function_string(" ");
...
return (tests_passed == number_of_tests); 

这只是一个如何做到这一点的例子(在我们公司,我们就是这样做的)。 此外,为非程序员或新人添加新测试也不是很难。