我如何测试这个抛出异常的方法?

huangapple 未分类评论45阅读模式
英文:

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&lt;T extends Food&gt; extends Product implements Placeable {

	public HashSet&lt;T&gt; content;

	public Box(int serialID, double price, String productName) {
		super(serialID, price, productName);
		this.content = new HashSet&lt;T&gt;();

	}

	@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 &gt; 3) {
			System.out.println(&quot;Too much Content. Nothing added.&quot;);
		} else {

			for (int i = 0; i &lt; 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&lt;Cake&gt; testBox = new Box&lt;Cake&gt;(1, 0.50, &quot;testBox&quot;);
		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);

	}

huangapple
  • 本文由 发表于 2020年7月25日 20:10:25
  • 转载请务必保留本文链接:https://java.coder-hub.com/63088160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定