如何为需要输入并因此调用其他函数的函数编写单元测试?

假设我有这个代码。真的不确定如何对它进行单元测试,因为它是一个无效方法,需要用户输入,并且其中一种情况的有效答案是调用另一种方法。比如我如何测试这个?

def start():
    user_Response = input(
        '\n' "○ Press 1 to Enter the Main Menu" '\n'
        "○ Press 2 or type 'exit' to Exit \n ")

    if user_Response == str(1):
        mainmenu()

    elif user_Response == str(2) or user_Response.lower() == "exit":
        print(
            'Thank you,good bye.
        exit()

    else:
        "Please enter a valid response."
        start() ```

xiaobestavril 回答:如何为需要输入并因此调用其他函数的函数编写单元测试?

我会重写这个函数。我不会调用 input,而是将类似文件的对象作为参数传递,您可以对其进行迭代。调用者可以负责传递 sys.stdin 或其他一些类似文件的对象(例如 io.StringIO 的实例)以方便测试。

我也会放弃递归,转而使用简单的循环。

def start(input_stream):
    while True:
        print("...")
        user_response = input_stream.readline().rstrip('\n')

        if user_response == "1":
            return mainMenu()

        elif user_response == "2" or user_response.lower() == "exit":
            print('Thank you,good bye.')
            exit()

        else:
            print("Please enter a valid response.")
        

示例测试:

def test_loop():
    try:
        start(io.StringIO("exit"))
    except SystemExit:
        pass
    else:
        assert False,"start did not exit"

         
本文链接:https://www.f2er.com/572.html

大家都在问