如何在 Python 中模拟用户输入

Py.*_*dan 4 python tdd unit-testing mocking python-mock

我目前正在尝试学习如何使用 Python 进行单元测试,并了解了 Mocking 的概念,我是一名初学者 Python 开发人员,希望在发展 Python 技能的同时学习 TDD 的概念。我正在努力学习使用Python unittest.mock 文档的用户给定输入来模拟类的概念。如果我能得到一个如何模拟某个函数的例子,我将非常感激。我将使用此处找到的示例:示例问题

class AgeCalculator(self):

    def calculate_age(self):
        age = input("What is your age?")
        age = int(age)
        print("Your age is:", age)
        return age

    def calculate_year(self, age)
        current_year = time.strftime("%Y")
        current_year = int(current_year)
        calculated_date = (current_year - age) + 100
        print("You will be 100 in", calculated_date)
        return calculated_date
Run Code Online (Sandbox Code Playgroud)

请有人使用 Mocking 创建一个示例单元测试来自动输入年龄,以便它返回模拟年龄为 100 的年份。

谢谢。

Men*_* Li 5

您可以在Python3.x中模拟buildins.input方法,并使用with语句来控制模拟期间的范围。

import unittest.mock
def test_input_mocking():
    with unittest.mock.patch('builtins.input', return_value=100):
         ...
Run Code Online (Sandbox Code Playgroud)