2013-10-16 42 views
1

测试应该能够很好地涵盖此类可以抛出的异常和错误的类型,并且它应该在CalculatePrimesMother的构造方法中覆盖有问题的语句。JUnit测试用例的最大覆盖范围

为三个JUnit测试案例所需的方法如下:

public CalculatePrimesMother(int numWorkers, int queueLength, int maxPrime, 
      boolean verbose) { 

     this.numWorkers = numWorkers; 

     // Instantiate 3 queues, for thread-safe communication with workers 
     Candidate = new ArrayBlockingQueue<Integer>(queueLength); 
     Prime = new ArrayBlockingQueue<Integer>(queueLength); 
     Composite = new ArrayBlockingQueue<Integer>(queueLength); 

     this.maxPrime = maxPrime; 
     this.sqrtMaxPrime = (int) Math.sqrt(maxPrime); 
     primeFactors = new int[sqrtMaxPrime]; 
     this.verbose = verbose; 
    } 

我试图创造一些测试情况,但没能获得全覆盖谁能帮助我?

public class CalculatePrimesMotherTest extends TestCase { 

    public CalculatePrimesMotherTest(String name) { 
     super(name); 
    } 

    private CalculatePrimesMother testMother; 

    @Test 
    public final void testCalculatePrimesMotherNegativequeueLength() { 
     try { 
      testMother = new CalculatePrimesMother(4, -12, 908, false); 
     } catch (Exception e) { 
      e.printStackTrace(); 

     } 

    } 

    @Test 
    public final void testCalculatePrimesMotherMinusOne() { 
     try { 
      testMother = new CalculatePrimesMother(8, 12, 0, true); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 
+0

您的构造函数中没有分支,因此只需调用新的CalculatePrimesMother就可以完全覆盖构造函数方法。你用什么工具计算覆盖率?声称哪些行未被此工具覆盖? –

+1

如果您没有得到全面覆盖,那必须是因为引发了异常,并且您正在测试中捕获它。这是你不应该做的事情。这个想法是让jUnit捕获代码中抛出的所有异常,以便它可以检测到测试是否失败。 – luanjot

回答

1

你会得到什么报道?在你的ctor中没有如果测试,所以一个调用应该执行我所看到的所有代码。

你写的代码太多了。 setUp和tearDown和测试构造函数方法都是不必要的。删除它们。

在其他测试中不需要try/catch块。也删除这些。您想要引发测试失败的异常。捕捉会隐藏错误。

+0

我想检查该方法的所有可能场景。所以所有可能的错误或异常情况应该在那里。 – user2886707

+0

你做到了。我看到没有检查异常被抛出。是什么让你觉得你没有100%的覆盖率?有没有一种工具可以给你一个指标,或者只是你想象你错过了什么? – duffymo

+1

@ user2886707这不是你在做什么。你告诉jUnit,如果有例外,他应该忽略它!如果您想考虑所有可能的异常,则应使用“预期”注释。检查了这一点http://www.vogella.com/articles/JUnit/article.html – luanjot

相关问题