0

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);

    }
nikva
  • 49
  • 5
  • 1
    As an aside: A test should test one thing, and one thing only. Thus, passing `null` as an argument and expecting an `Exception` to be thrown should be a separate test. – Turing85 Jul 25 '20 at 12:12
  • looks like it does but there are some operators that i dont really get. – nikva Jul 25 '20 at 12:14
  • [Let's continue the discussion in chat](https://chat.stackoverflow.com/rooms/218577/room-for-turing85-and-nikva9.) – Turing85 Jul 25 '20 at 12:19

0 Answers0