假设我有这个代码。真的不确定如何对它进行单元测试,因为它是一个无效方法,需要用户输入,并且其中一种情况的有效答案是调用另一种方法。比如我如何测试这个?
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() ```
答案 0 :(得分:0)
我会重写这个函数。我不会调用 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"