Reputation: 41
I am doing an assignment for a course, I need to get full coverage of this method
These are the attributes and the constructor, it is a program for a coffee machine, this is the Recipe class
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;
}
I've used
/*
* 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");
}
The recipeException doesn't seem to be catching when I use RecipeException and even thought I know it's going to be thrown the coverage doesn't get to the entire method.
This class is the only one left with not full coverage and this RecipeException doesn't seem to be cathing.
How should I do the test when the RecipeException is thrown so it gets full coverage?
This code belongs to the course edu.ncsu.csc326.coffeemaker
Upvotes: 3
Views: 2940
Reputation: 162
Your test is failing because in the testSetPrice_2 method, the initial invocation of r1.setPrice("adsada");
causes a NumberFormatException
to be thrown which interrupts the execution of the test ...
r1.setPrice(" ");
r1.setPrice("-1");
are thus never run. To resolve this you need to make each invocation of r1.setPrice(...)
a separate test method, e.g. as shown below:
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");
}
}
Upvotes: 5