白盒测试之单元测试用例设计入门
// 实验存档
ServiceForTesting.java:
package ex3; public class ServiceForTestingImpl implements ServiceForTesting { /** * 手机配件销售佣金结算函数 * @param headphones 耳机 * @param shells 外壳 * @param protectors 保护膜 * @return 佣金 */ public float getCommission(int headphones, int shells, int protectors) { float salary; float total; if (headphones <= 0 || shells < 0 || protectors < 0) { return (float) -1; } total = headphones * 80 + shells * 10 + protectors * 8; if (total < 1000) { salary = total * (float) 0.1; } else if (total < 1800){ salary = 1000 * (float) 0.1 + (total - 1000) * (float) 0.15; } else { salary = 1000 * (float) 0.1 + 800 * (float) 0.15 + (total - 1800) * (float) 0.2; } return salary; } }
/
Test.java:
package ex3; import org.junit.Test; import static org.junit.Assert.*; public class WhiteBoxUnitTestCases { private ServiceForTesting service = new ServiceForTestingImpl(); @Test public void statementCoverage() { decisionCoverageOrBranchCoverage(); } @Test public void decisionCoverageOrBranchCoverage() { float output1 = service.getCommission(0, 1, 1); // 数量不合法 float output2 = service.getCommission(1, 2, 3); // < 1000 float output3 = service.getCommission(10, 20, 20); // < 1800 float output4 = service.getCommission(20, 40, 40); // >= 1800 assertEquals(-1, output1, 0.01); assertEquals(12.4, output2, 0.01); // actual:12.400001 assertEquals(124.0, output3, 0.01); assertEquals(324.0, output4, 0.01); } @Test public void conditionCoverage() { /* 确保每个判定中的每个条件都获得可能的取值, 即每个条件至少有一次真值、有一次假值。 */ decisionConditionCoverage(); } @Test public void decisionConditionCoverage() { // Decision/Condition Coverage /* Decision/Condition Coverage 保证每个Decision取一次真假,并且每个Condition也取一次真和假 */ /* 条件(共5个):①headphones <= 0 ②shells < 0 ③protectors < 0 ④total < 1000 ⑤total < 1800 取值1:1 (后续判定不会执行) 取值2:0 1 (后续判定不会执行) 取值3:0 0 1(后续判定不会执行) 取值4:0 0 0 1(最后一个判定不会执行) 取值5:0 0 0 0 1 取值6:0 0 0 0 0 */ assertEquals(-1, service.getCommission(-1, 1, 1), 0.01); assertEquals(-1, service.getCommission(1, -1, 1), 0.01); assertEquals(-1, service.getCommission(1, 1, -1), 0.01); assertEquals(81.8, service.getCommission(10, 1, 1), 0.01); // total=818.0 assertEquals(192.7, service.getCommission(20, 1, 1), 0.01); // total=1618.0 assertEquals(343.6, service.getCommission(30, 1, 1), 0.01); // total=2418.0 } @Test public void multipleConditionCoverage() { // Branch Condition Combination Coverage // 略。由 0 0 0 0 0 列举到 1 1 1 1 1 共 2^5 组测试用例 } @Test public void MC_DC() { // Modified Condition/Decision Coverage // multipleConditionCoverage的子集 // 核心意思是每个条件都要独立影响判定结果。 // 对于一般企业来说,建议用MC/DC作为统一的覆盖标准。 decisionConditionCoverage(); } @Test public void pathCoverage() { // 覆盖从开始到结束的所有路径 decisionConditionCoverage(); } }