我是代码覆盖率的新手,我试图让我的单元测试覆盖 %100 的代码。
我的第一个问题是,这可能/可行吗?
我的第二个更具体的问题是,我有以下方法:
/// <summary>
/// Clears frames, control groups, display groups
/// </summary>
public bool Clear()
{
try
{
this.Frames.Clear();
this.ControlGroups.Clear();
this.DisplayGroups.Clear();
return true;
}
catch (Exception ex)
{
Milltown.MTCore.mtException mtEx = new Milltown.MTCore.mtException((int)PFExceptions.Exception_Hidden_FuctionLevel, ex,
PFCommonVariables.ApplicationPlatform, PFCommonVariables.ApplicationDataSource, "PFSystem:Clear");
return false;
}
}
我对这种方法的单元测试是:
//System Clear Test
Assert.IsTrue(MySystem.Clear());
Assert.AreEqual(0,MySystem.Frames.Count);
Assert.AreEqual(0,MySystem.ControlGroups.Count);
Assert.AreEqual(0, MySystem.DisplayGroups.Count);
代码覆盖率显示我覆盖了 try 块内的行,但未覆盖 catch 块。如何覆盖 catch 块中的代码?
最佳答案
改善您的覆盖面是一个很好的目标。不要过于关注 100% 的数字:它可能会产生误导。更多的覆盖比更少的好,但即使是 100%,你也可能会遗漏代码的许多方面(参见 http://nedbatchelder.com/blog/200710/flaws_in_coverage_measurement.html 以获取 Python 中的示例)。最后 5% 的报道可能不会像您希望的那样告诉您。
至于您的异常,您需要一种方法来强制从您的方法之一抛出异常。执行此操作的常用方法是模拟实现,以便您可以决定子对象在测试期间实际执行的操作,而无需绑定(bind)到特定实现。
关于exception - 如何在 Visual Studio Code Coverage 中覆盖异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3284470/