如何获得Java Code Coverage的完整报道? Junit测试用例

问题描述

我正在为一门课程做作业,我需要全面了解这种方法

Image of code coverage in Eclipse using JaCoco

这些是属性和构造函数,它是咖啡机的程序,这是Recipe类

for i in range(0,15):
    if i == 3:
       continue
    print(i)

我用过

public class Recipe {
private String name;
private int price;
private int amtCoffee;
private int amtMilk;
private int amtSugar;
private int amtChocolate;

/**
 * Creates a default recipe for the coffee maker.
 */
public Recipe() {
    this.name = "";
    this.price = 0;
    this.amtCoffee = 0;
    this.amtMilk = 0;
    this.amtSugar = 0;
    this.amtChocolate = 0;
}

当我使用RecipeException时,似乎并没有捕获到食谱异常,甚至以为我知道它会被抛出,因此覆盖范围并不能覆盖整个方法

该类是剩下的唯一一个未完全覆盖的类,并且此RecipeException似乎没有多余的内容

引发RecipeException使其完全覆盖时,我应该如何进行测试?

代码属于课程edu.ncsu.csc326.coffeemaker

解决方法

您的测试失败,因为在testSetPrice_2方法中,r1.setPrice("adsada");的初始调用会导致抛出NumberFormatException,从而中断测试的执行...

    r1.setPrice(" ");
    r1.setPrice("-1");
因此

永远不会运行。要解决此问题,您需要每次调用r1.setPrice(...)

一种单独的测试方法,例如如下所示:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

public class RecipeTest {
    Recipe r1;

    @Before
    public void setUp() throws Exception {
        r1 = new Recipe();
    }

    @Test
    public void testSetPriceValid_1() throws RecipeException {
        r1.setPrice("25");
    }

    @Test
    public void testSetPriceValid_2() throws RecipeException {
        r1.setPrice("0");
    }

    @Test(expected = RecipeException.class)
    public void testSetPriceInvalid0() throws RecipeException {
        r1.setPrice("adsada");
    }

    @Test(expected = RecipeException.class)
    public void testSetPriceInvalid1() throws RecipeException {
        r1.setPrice(" ");
    }

    @Test(expected = RecipeException.class)
    public void testSetPriceInvalid2() throws RecipeException {
        r1.setPrice("-1");
    }

}