點覆蓋:即對程序的控制流圖節點進行全面覆蓋。
邊覆蓋:設計一條路徑,使程序的控制流圖中所有邊被覆蓋。
主路徑覆蓋:就是對程序設計測試用例,使測試用例盡可能多的經過控制流圖中的邊同時不形成環。
習題:
對以下代碼進行分析:
package com.prime; public class Prime { public static Boolean isDivisable(int prime, int curPrime) { if (curPrime % prime == 0) { return true; } else return false; } public static void printPrimes(int n) { int curPrime; // Value currently considered for primeness int numPrimes; // Number of primes found so far. boolean isPrime; // Is curPrime prime? int[] primes = new int[100]; // The list of prime numbers. // Initialize 2 into the list of primes. primes[0] = 2; numPrimes = 1; curPrime = 2; while (numPrimes < n) { curPrime++; // next number to consider ... isPrime = true; for (int i = 0; i <= numPrimes - 1; i++) { // for each previous // prime. if (isDivisable(primes[i], curPrime)) { // Found a divisor, // curPrime is not // prime. isPrime = false; break; // out of loop through primes. } } if (isPrime) { // save it! primes[numPrimes] = curPrime; numPrimes++; } } // End while // Print all the primes out. for (int i = 0; i <= numPrimes - 1; i++) { System.out.println("Prime: " + primes[i]); } } // end printPrimes }
問題a:畫出程序的控制流圖
問題b:設計一個錯誤,使測試用例t2(n=5)比t1(n=3)更容易發現的錯誤。
將程序中n換成4,這樣測試用例n=3不能發現這個錯誤而n=5能發現。
問題c:測試用例 t(n=1)
問題d:
點覆蓋:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
邊覆蓋:[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,5),(6,8),(8,9),(5,9),(9,10),(10,11),(11,2),(2,12),(12,13),(13,14),(14,15),(15,13),(13,16)]
主路徑覆蓋:
[1,2,3,4,5,6,7]
[1,2,3,4,5,9,10,11]
[1,2,3,4,5,9,11]
[1,2,3,4,5,6,8,9,10,11]
[1,2,3,4,5,6,8,9,11]
[1,2,12,13,14,15]
[1,2,12,13,16]
[2,3,4,5,6,8,9,10,11,2]
[2,3,4,5,6,8,9,11,2]
[2,3,4,5,9,10,11,2]
[2,3,4,5,9,11,2]
[3,4,5,6,8,9,10,11,2,12,13,14,15]
[3,4,5,6,8,9,10,11,2,12,13,16]
[3,4,5,6,8,9,11,2,12,13,14,15]
[3,4,5,6,8,9,11,2,12,13,16]
[3,4,5,9,10,11,2,12,13,14,15]
[3,4,5,9,11,2,12,13,14,15]
[3,4,5,9,10,11,2,12,13,16]
[3,4,5,9,11,2,12,13,16]
[5,6,7,5]
[6,7,5,9,10,11,2,12,13,14,15]
[6,7,5,9,11,2,12,13,14,15]
[6,7,5,9,10,11,2,12,13,16]
[6,7,5,9,11,2,12,13,16]
[13,14,15,13]
[14,15,13,16]
設計測試代碼如下:
package Primay; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.*; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; //import org.junit.internal.runners.TestClassRunner; import org.junit.runner.RunWith; import Primay.Primaies; public class PrimaiesTest { public static Primaies primay = new Primaies(); @Before public void Start() throws Exception{ primay.Start(); } @After public void End() throws Exception{ } @Test public void TestNormal(){ String str=new String("Prime: 2\r\nPrime: 3\r\nPrime: 5\r\nPrime: 7\r\nPrime: 11\r\n"); primay.printPrimes(5); assertEquals(str,primay.Getstr()); } }
設計時將源代碼輸出到控制台改變為輸出到Primaies類中一個私有成員變量,String類型,每次測試對此變量初始化。
然后測試比較成員變量中與預測結果是否一致。
具體代碼上傳至git中TestJunit項目中:https://github.com/klkjjhjkhjhg/junit
效果圖如下:
程序代碼率:
由於本項目中含有其他文件,所以代碼率不是100%