使用用户输入验证对方法进行单元测试

时间:2018-12-08 23:36:07

标签: python python-2.7 unit-testing tdd

我有一种方法可以接收用户输入并对其进行验证,直到输入正确的值为止。我不确定如何为此方法编写单元测试,因为它已经验证了用户输入。

def refreshtime_validation():
    while True:
        try:
            runtime_input = float(raw_input("Enter Refresh Time (in seconds): "))
        except ValueError:
            print "\n**Please enter a valid number (Must be an integer).**\n"
            continue
        if runtime_input <= 0:
            print "\n**Please enter a valid number (Must be greater than 0).**\n"
            continue
        else:
            return runtime_input

如何为这种方法编写单元测试?到目前为止,我唯一的一个是

self.assertEquals('1','1')    
self.assertEquals('100','100')
self.assertEquals('100000','100000')

1 个答案:

答案 0 :(得分:3)

您可以使用mockmock a raw_input in Python,也可以capture standard output by redirecting sys.stdout to a StringIO。这样,您可以模拟函数输入并测试无效和有效的情况:

def generate_sequence
  n = gets.chomp.to_i
  i = 0
  while i < 4
    n = n * 4
    p n
    i = i + 1
  end
end