如何对if else语句进行单元测试

本文关键字:单元测试 语句 else if | 更新日期: 2023-09-27 18:11:15

我有以下方法。我如何为这个函数编写单元测试以确保机器被添加到修理列表中?

public void AddMachineToRepairsList()
{
    Console.WriteLine("Would you like to add this Machine to the repairs list?");
    var addToRepairs = Console.ReadLine().ToLower();
    if (addToRepairs == "yes")
    {
        int cost = 0;
        int hoursWorked = 0;
        var machine = new Repair(cost, hoursWorked);
        Repairs.Add(machine);
        Console.WriteLine("Machine successfully added!");
    }
    else
    {
        Console.WriteLine("Please enter machine information again");
        this.Run();
    }     
}

如何对if else语句进行单元测试

您需要将addtorepair作为参数传递给方法并调用

    Console.WriteLine("Would you like to add this Machine to the repairs list?");
    var addToRepairs = Console.ReadLine().ToLower();
    while(AddMachineToRepairsList(addToRepairs)==false) 
{
 Console.WriteLine("Please enter machine information again");
    this.Run();
}

定义为

public bool AddMachineToRepairsList(string option)
{
    string addToRepairs = "";
    if (addToRepairs == "yes")
    {
        int cost = 0;
        int hoursWorked = 0;
        var machine = new Repair(cost, hoursWorked);
        Repairs.Add(machine);
        Console.WriteLine("Machine successfully added!");
        return true;
    }
    else
    {
        return false;
    }
}

现在一个单元测试的值是"yes",另一个是"no"。你可以编写单元测试,并根据传入的选项断言返回值为true/false