![](/img/trans.png)
[英]How to get full coverage for Java Code Coverage? Junit 5 Eclipse IDE
[英]How to get full coverage for Java Code Coverage? Junit test cases
我正在為一門課程做作業,我需要全面了解這種方法
這些是屬性和構造函數,它是咖啡機的程序,這是 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");
導致拋出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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.