c# 关于throw的unit test 写法
在做unit test时,发现有的try,catch语句中会有throw语句,虽然观察同事的代码中对于这样的语句通常不做测试,但有时因为特殊要求或者干脆为了追求测试百分比,还是要学会如何进行测试,记录一下今天学到的测试方法。
原理:当程序进入需要测试的原代码中并运行到throw语句时,如果上一层语句中也有throw语句,那么将不会直接返回error,而是会跳转到上一层语句的throw语句中。所以,我们只需要在测试程序的语句中加入throw语句,并设置好应有的Assert语句即可。
例子:
原程序:
public void test()
{
try
{
//do something
}
catch(Exception ex)
{
throw new Exception(some message);
}
}
unit test:
bool testresult = true;
try
{
var result = test();
Assert.AreEqual(testresult,false);
}
catch
{
Assert.AreEqual(testresult,true);
}
今天写test时突然意识到,有的catch后面会跟着Exception,也就意味着返回上一层的throw中会有错误的详细信息,这种情况下,代码改为下面的写法会更为准确。
unit test:
bool testresult = true;
try
{
var result = test();
Assert.AreEqual(testresult,false);
}
catch(Exception ex)
{
Assert.AreEqual(ex.message,相应的错误信息);
}