bug经验分享,同时分析单元测试带来好处的一个实际小例子

最近项目出现了一个小bug,后来找到原因是下面这一小段代码导致的。由于代码有一定的重复性,所以在copy的时候有一处忘记了修改,下面有两个对ExportCommonCsv的判断。当时没有对这段代码进行单元测试,review也没有看出来,手动测试也没有测试足够的用例所以没覆盖到。

private int GetExportCategoryCount()
        {
            int sum = 0;
            if (this.ExportCommonXml)
            {
                sum++;
            }
            if (this.ExportCommonCsv)
            {
                sum++;
            }
            if (this.ExportMonthlyXml)
            {
                sum++;
            }
            if (this.ExportCommonCsv)
            {
                sum++;
            }
            if (this.ExportAllInOneXml)
            {
                sum++;
            }
            if (this.ExportAllInOneCsv)
            {
                sum++;
            }
            return sum;
        }

 

对这个函数进行单元测试其实很简单,把这些属性全部设为true然后调用一下看返回是不是6就可以了,代码覆盖率100%。为了测试的更全面可以再加一个全部是false和一部分是true的情况,几分钟就可以写完。

public void GetExportCategoryCountTest_All()

{

DataExport_Accessor target = new DataExport_Accessor();

target.ExportMonthlyCsv = true;

target.ExportMonthlyXml = true;

target.ExportCommonCsv = true;

target.ExportCommonXml = true;

target.ExportAllInOneCsv = true;

target.ExportAllInOneXml = true;

int expected = 6;

int actual;

actual = target.GetExportCategoryCount();

Assert.AreEqual(expected, actual);

}
posted @ 2012-11-20 17:18  xinbin  阅读(225)  评论(1)    收藏  举报