Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python和unittest库测试函数调用_Python_Unit Testing_Python Unittest_Python Mock - Fatal编程技术网

如何使用Python和unittest库测试函数调用

如何使用Python和unittest库测试函数调用,python,unit-testing,python-unittest,python-mock,Python,Unit Testing,Python Unittest,Python Mock,我刚才有个问题,关于如何为下面的函数编写测试?下面是我对所涉及部分的测试,但我不确定如何更改测试以覆盖print语句并再次调用get\u employee\u name函数。任何帮助都将不胜感激 以下是我测试所涵盖部分的代码: DATA = { "employee_name": "Brian Weber", "minutes": 120, "task_name": "Surfing", "notes": "These are my notes.", "date": "2016-12-25" }

我刚才有个问题,关于如何为下面的函数编写测试?下面是我对所涉及部分的测试,但我不确定如何更改测试以覆盖print语句并再次调用
get\u employee\u name
函数。任何帮助都将不胜感激

以下是我测试所涵盖部分的代码:

DATA = {
"employee_name": "Brian Weber",
"minutes": 120,
"task_name": "Surfing",
"notes": "These are my notes.",
"date": "2016-12-25"
}
​
​
class WorkLogTests(unittest.TestCase):
    def test_get_employee_name(self):
        with mock.patch('builtins.input',
            return_value=DATA["employee_name"]):
            assert worklog.get_employee_name() == DATA["employee_name"]

我遇到的第一个问题是,如果用户没有输入任何内容,就使用递归。所以我重构了代码,在没有用户输入的情况下使用continue来使用while循环。 以下是涵盖所有行的新代码和测试:

def get_employee_name():
    """Prompt the employee for their name."""
    while True:
        employee_name = input("Enter employee name: ")
        if len(employee_name) == 0:
            print("\nYou must enter your name!\n")
            continue
        else:
            return employee_name

def test_get_employee_name(self):
    with mock.patch('builtins.input', side_effect=["", "Brian Weber"],
        return_value=DATA["employee_name"]):
        assert worklog.get_employee_name() == DATA["employee_name"]

真正地那么,您认为在什么情况下会执行这些行呢?如果没有输入,那么代码的这一部分就会运行。很抱歉新来这里测试。不,我不是这么说的。如果要覆盖这些行,则需要使用不同的输入数据编写另一个测试。这将说明当前实现失败的原因。另外,请注意递归并不是最好的方法;请参见,例如,Ok,那么我是否会使用“副作用”属性来使用不同的输入数据?我只是对如何编写测试的语法感到困惑。你试过了吗?怎么搞的?