测试Void方法对象和事件参数

时间:2016-04-14 18:54:55

标签: c# unit-testing

我不知道如何在C#程序中测试我的calc,因为我的方法与(object sender,EventArgs e)参数和全局变量完全一致。怎么测试这个方法看起来像?

这只是代码的一部分

private void buttonEq_Click(object sender, EventArgs e)
{

    number2 = int.Parse(textBox1.Text);

    if (operation == "plus")
    {
        finRes = number1 + number2;
    }
    else if (operation == "minus")
    {
        finRes = number1 - number2;
    }
    else if (operation == "multiple")
    {
        finRes = number1 * number2;
    }
    else if (operation == "divide")
    {
        finRes = number1 / number2;
    }
    else if (operation == "exp")
    {
        finRes = Math.Pow(number1, number2);
    }
    else if (operation == "fac")
    {
        int result = number1;

        for (int i = (number1)-1; i > 0 ; i--)
        {
            result = result * i;    
            finRes = result;
        }
    }
    else if (operation == "sqrt")
    {
        finRes = Math.Sqrt(number1);
    }

    textBox2.Text = finRes.ToString();
    operation = "";
}

1 个答案:

答案 0 :(得分:2)

如果要使计算逻辑可测试,则需要重构代码。简单来说,这意味着将所有if / else分解为单独的方法。现在,您可以测试Calculate方法,或者只是从事件处理程序中调用它,无论如何。

void Calculate(int num1, int num2)
{
   // put all your if / else logic here
}

void buttonEq_Click(object sender, EventArgs e)
{
   Calculate(number1, number2);
}