一、完成习题中的问题
对于这样的一组程序方法,回答下列问题:
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 MAXPRIMES = 100; int [] primes = new int [MAXPRIMES]; // The list of prime numbers //Initialize 2 into the list of primes primes [0] = 2; numPrimes = 1; curPrime = 2; while (numPrimes < n) { curPrime++; // next numberto consider... isPrime = true; for (int i = 0; i <= numPrimes-1; i++) { if (curPrime % primes[i] == 0) { isPrime = false; break; } } if (isPrime) { primes[numPrimes] = curPrime; numPrimes++; } } for (int i = 0; i <= numPrimes-1; i++) { System.out.println("Prime: " + primes[i]); } }
a.画出这个方法的控制流图
b.考虑测试用例t1=(n=3)和t2=(n=5)。即使这些测试用例游历printPrimes()方法中相同的主路径,它们不一定找出相同的错误。设计一个简单的错误,是的t2比t1更容易发现。
当n=4的时候,t2会发生数组越界错误而t1不会。
c.针对printPrimes(),找到一个测试用例,使得相应的测试路径访问连接while语句开始到for语句的边,而不用通过while循环体。
当n=1的时候,会直接跳过while循环体而直接打印出for循环语句的内容
d.针对printPrimes()的图例举每个节点覆盖、边覆盖和主路径覆盖的测试需求。
节点覆盖:{1,2,3,4,5,6,7,8,9,10,11}
边覆盖:{(1,2), (2,3), (2,9), (3,4), (4,7), (4,5), (5,6), (5,4), (6,4), (7,8), (7,9), (8,9), (9,10), (10, 11), (11,10), (10, end)}
主路径覆盖:
{(1,2,9,10,e), (1,2,3,4,7,9,10,e), (1,2,3,4,7,8,9,10,end),
(4,5,4), (4,5,6,4),
(5,4,5), (5,4,7,9,10,end), (5,4,7,8,9,10,end), (5,6,4,7,9,10,end), (5,6,4,7,8,9,10,end), (5,6,4,5),
(6,4,5,6), (6,4,7,9,10,end), (6,4,7,8,9,10,end),
(10,11,10), (11, 10, 11), (11,10,end)}
二.基于Junit及Eclemma(jacoco)实现一个主路径覆盖的测试。
代码结构如下:
其中Prime.java如下:
package prime; public class Prime { 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 MAXPRIMES = 100; int [] primes = new int [MAXPRIMES]; // The list of prime numbers //Initialize 2 into the list of primes primes [0] = 2; numPrimes = 1; curPrime = 2; while (numPrimes < n) { curPrime++; // next numberto consider... isPrime = true; for (int i = 0; i <= numPrimes-1; i++) { if (curPrime % primes[i] == 0) { isPrime = false; break; } } if (isPrime) { primes[numPrimes] = curPrime; numPrimes++; } } for (int i = 0; i <= numPrimes-1; i++) { System.out.println("Prime: " + primes[i]); } } }
PrimeTest.java如下:
import static org.junit.Assert.*; import org.junit.Test; import prime.Prime; public class PrimeTest { Prime p = new Prime(); @Test public void testPrintPrimes() { p.printPrimes(7); } }
最终得出的测试覆盖结果如下: