unit-testing - 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 进行测试时,它会加载无限长。有谁知道如何编写测试来解决这个问题?一个全新的测试也很棒,或者使用模拟模块。如果有人可以为此代码提供一些测试,那就太棒了!提前致谢!
解决方案
推荐阅读
- node.js - 如何在 node.js 中实现数字签名
- git - Where to put user-project specific Gradle properties?
- javascript - 限制 ocr 扫描的图像大小
- service-worker - Workbox Service Worker 未在缓存中存储图像和 API 响应
- javascript - 将参数传递给动态导入反应
- json - 如何在 Swift 中为常量 Decodable 对象动态添加属性?
- spring - 如何使用 Spring Rest 修复 Google App Engine 中的未经授权的错误?
- c# - 将演示文稿添加到新打开的 PowerPoint 应用程序 - 例外
- php - Preg_replace 在 php 中无法正常工作为 $(dollar) 符号
- makefile - 从 Makefile 规则打印粗体或彩色文本