我有一个基于函数构建的程序,该函数在函数内部获取用户输入而不是函数前的参数:例如,假设我的函数是
def my_function():
a = input("a: ")
b = input("b: ")
print(a+b)
根据我目前对单元测试的理解,这样的函数比像这样工作的函数更难进行单元测试:
def another_function(a,b):
return(a+b)
例如,我该如何着手测试一个看起来像 my_function 的函数?感觉好像通过输入错误的输入并检查错误来手动测试很容易,但我必须编写一个测试套件来自动测试我的所有功能。
请您参考如下方法:
鉴于您的函数输入来自 input 并且输出转到 print,您将不得不“模拟”这两个函数以测试 my_function。例如,使用简单的手动模拟:
def my_function(input=input, print=print):
a = input("a: ")
b = input("b: ")
print(a+b)
if __name__ == '__main__':
inputs = ['hello', 'world']
printed = []
def mock_input(prompt):
return inputs.pop(0)
def mock_print(text):
printed.append(text)
my_function(mock_input, mock_print)
assert len(inputs) == 0, 'not all input used'
assert len(printed) == 1, '{} items printed'.format(len(printed))
assert printed[0] == 'helloworld'
当您将此与以下内容进行比较时:
assert my_function('hello', 'world') == 'helloworld'
您会明白为什么后者更受青睐!
您还可以使用适当的模拟库来更巧妙地完成此操作,而无需提供函数作为参数;参见例如How to supply stdin, files and environment variable inputs to Python unit tests? .
