英文:
How do i Test this Exception throwing method?
问题
@Test
void addFoodsTest() {
Box<Cake> testBox = new Box<Cake>(1, 0.50, "testBox");
Cake cake1 = new Cake(Flavour.CHOCLATE, 20);
Cake cake2 = new Cake(Flavour.VANILLA, 30);
Cake cake3 = new Cake(Flavour.STRAWBERRY, 20);
Cake cake4 = new Cake(Flavour.CHOCLATE, 30);
assertEquals(1, testBox.addFoods(cake1));
testBox.addFoods(cake1, cake2, cake3, cake4);
assertThrows(NothingToAddException.class, () -> {
testBox.addFoods((Cake)null);
});
}
英文:
I have the combination of 2 methods that add objects into a hashset. If the param is null, it throws a NothingToAddException. How can i test this case with Junit5 Tests? I need to get the method tested to 100%
package edu.hm.cs.swe2.products;
import java.util.HashSet;
import java.util.Iterator;
import edu.hm.cs.swe2.exceptions.NothingToAddException;
import edu.hm.cs.swe2.food.Food;
public class Box<T extends Food> extends Product implements Placeable {
public HashSet<T> content;
public Box(int serialID, double price, String productName) {
super(serialID, price, productName);
this.content = new HashSet<T>();
}
@Override
public int getProductSerial() {
return this.getSerialID();
}
public void addFood(T food) throws NothingToAddException {
if (food == null) {
throw new NothingToAddException();
}
content.add(food);
}
public int addFoods(T... foodsToAdd) {
int foodsAdded = 0;
if (foodsToAdd.length > 3) {
System.out.println("Too much Content. Nothing added.");
} else {
for (int i = 0; i < foodsToAdd.length; i++) {
try {
this.addFood(foodsToAdd[i]);
foodsAdded++;
} catch (NothingToAddException e) {
}
}
}
return foodsAdded;
}
this is my testmethod so far where i already tested the usual cases
@Test
void addFoodsTest() {
Box<Cake> testBox = new Box<Cake>(1, 0.50, "testBox");
Cake cake1 = new Cake(Flavour.CHOCLATE, 20);
Cake cake2 = new Cake(Flavour.VANILLA, 30);
Cake cake3 = new Cake(Flavour.STRAWBERRY, 20);
Cake cake4 = new Cake(Flavour.CHOCLATE, 30);
assertEquals(1, testBox.addFoods(cake1));
testBox.addFoods(cake1, cake2, cake3, cake4);
testBox.addFoods(null);
}
专注分享java语言的经验与见解,让所有开发者获益!
评论