首页 > 解决方案 > while循环中的单元测试输入

问题描述

我是单元测试的新手,我正在尝试对我的代码进行单元测试。我的代码包含一个 while 循环和一个输入函数。在运行我的单元测试时,它会一直运行(可能是无限的 while 循环)。谁能给我发一段代码来对我文件的这小部分进行单元测试。

下面的代码:

import datetime
from win10toast import ToastNotifier


def hydration():
    interval = -1
    while interval <= 0:
        try:
            interval = int(input('How often do you want hydration reminders? \n'))
        except ValueError:
            print('The time interval should be an integer.')
        else:
            if interval <= 0:
                print('The time interval should be larger than 0.')
    return interval


因此,我尝试使用以下方法对此进行单元测试:

class MyTestCase(unittest.TestCase):
    def runTest(self, given_answer, expected_out):
        with patch('builtins.input', return_value=given_answer), patch('sys.stdout', new=StringIO()) as fake_out:
            project.NotificationSender.hydration()
            self.assertEqual(fake_out.getvalue().strip(), expected_out)

    def testNo(self):
        self.runTest('5', 'How often do you want hydration reminders?')

这仅适用于尝试后的第一个输入:当我在 runTest 中输入 5 时。在使用负数或 0 进行测试时,它会加载无限长。有谁知道如何编写测试来解决这个问题?一个全新的测试也很棒,或者使用模拟模块。如果有人可以为此代码提供一些测试,那就太棒了!提前致谢!

标签: unit-testingwhile-loopnotificationsmocking

解决方案


推荐阅读