JUnit 4 Expected Exception type

前端 未结 4 1950
無奈伤痛
無奈伤痛 2020-12-08 06:54

I am trying to do a JUnit test on code that someone else has written, but I cannot figure out how to test for the exception, because the exception seems to lack a type.

4条回答
  •  粉色の甜心
    2020-12-08 07:28

    I wouldn't throw an Exception if the gold isn't greater than or equal to zero. I would throw an IllegalArgumentException. It certainly sounds like it's illegal your Pirate to have a negative amount of gold.

    public Pirate(String name, int initialGold) {
        if(initialGold < 0)
            throw new IllegalArgumentException("Init Gold must be >= 0");
    

    Then in your JUnit test case, expect the IllegalArgumentException.

    @Test(expected=IllegalArgumentException.class)
    public static void exceptionTest() {
    

提交回复
热议问题