我有一个温度应用程序,它接受用户输入(什么单位、温度)以在不同的温度单位之间进行转换。它涉及通过正常的 str(input(xyz)) 和 float(input(123)) 类型的提示提示用户输入这些单位和数字,之后应用程序的其余部分获取该数据并使用它来执行任务,从一些基本的手动测试中我发现它是正确的。
我想练习使用 unittest 为我的应用程序编写单元测试,所以也写了那些(我相信也是正确的)。测试按预期通过。然而,我的问题是,即使我提供了测试在测试本身内工作所需的数据,我仍然会在我的主应用程序中完成输入提示。虽然我可以按 enter 键跳过它并且测试将按预期进行,但我宁愿找到一些方法让 unittest 自己填写这些输入提示,完全绕过该输入位,或者至少将其静音,这样我就不会每次都必须运行我所有的输入提示。可以用 unittest 做到这一点吗?
这是我为我的主要应用程序编写的基本结构
def main():
unit_from, unit_to, temperature = user_input
# continues with the rest of the application using above data...
#function to get user input
def user_input():
#gets user input using str and float prompts.
#and then returns those values for use in the rest of the program
main()
对于单元测试:
import unittest
#module containing classes where the formulas for conversion live
import temperature
#main application that utilzes temperature classes and drives it all
import temp_converter
class FahrenheitConvertTestCase(unittest.TestCase):
#one of my example tests
def test_f_to_c(self):
from_unit = 'FAHRENHEIT'
to_unit = 'CELSIUS'
temp = 32.0
t_convert = temperature.Fahrenheit(temp, from_unit, to_unit)
converted_temp = t_convert.convert()
self.assertEqual(converted_temp, 0.0)
请您参考如下方法:
当你有一个带有函数调用的模块时
main()
它将在导入模块时调用。
您可以通过将其包装在条件语句中来避免这种情况
if __name__ == '__main__':
main()
然后 main 只会在该模块作为主程序执行时被调用,而不是在导入时被调用。
