java - 如何获得 Java 代码覆盖率的全面覆盖?Junit 测试用例
问题描述
我正在为一门课程做作业,我需要全面了解这种方法
这些是属性和构造函数,它是咖啡机的程序,这是 Recipe 类
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;
}
我用过
/*
* setPrice test
*/
@Test
public void testSetPrice_1() throws RecipeException {
r1.setPrice("25");
r1.setPrice("0");
}
/*
* setPrice test
*/
@Test(expected = RecipeException.class)
public void testSetPrice_2() throws RecipeException {
r1.setPrice("adsada");
r1.setPrice(" ");
r1.setPrice("-1");
}
当我使用 RecipeException 时,recipeException 似乎没有被捕获,甚至认为我知道它会被抛出,但覆盖范围不会到达整个方法。
这个类是唯一一个没有完全覆盖的类,而且这个 RecipeException 似乎并不重要。
当 RecipeException 被抛出时,我应该如何进行测试以使其得到全面覆盖?
此代码属于课程 edu.ncsu.csc326.coffeemaker
解决方案
您的测试失败,因为在 testSetPrice_2 方法中,初始调用r1.setPrice("adsada");
会导致 aNumberFormatException
被抛出,从而中断测试的执行......
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");
}
}
推荐阅读
- ionic-framework - resolveLocalFileSystemURL TypeError:无法读取未定义 TypeError 的属性“then”
- javascript - 减少 ES6 函数中的对象数组
- firebase - 如何在firebase中的updateEmail后捕获“权限被拒绝”
- assembly - Mips,如何使用带有 lw 的偏移量获得一个 .word 中的第二个值
- r - 将列表列表转换为列表的数据框,其中子列表具有不同的行数
- delphi - 创建 SSL 上下文时出错 (140A90F1:lib(20):func(169):reason(241))
- c# - Listview 中的 UWP C# Toggleswitch - 单击 Toggleswitch 时如何获取行的项目
- python - 在 Python 上下文管理器中观察到的诡异动作
- cakephp-3.0 - Cakephp 3 修改集合的麻烦
- sql - 如何在 VBA 中使用 where 条件编写 select 语句