JUnit异常处理无法正常工作

时间:2017-11-25 11:20:40

标签: java maven junit exception-handling

我是单元测试的新手,我正在尝试学习JUnit。处理测试中的异常在我的项目中不起作用。这是我的班级:

public class Things {

  private int amount;
  private int[] weights;
  private int[] values;

  public Things(int amount, int[] weights, int[] values){
    this.amount = amount;
    if (amount!=weights.length || amount != values.length){
        throw new IllegalArgumentException("Amount of things different than weights or values length");
    }
    this.weights=weights;
    this.values=values;
  }
}

和测试类:

public class ThingsTest {

@Test
public void testThingsConstructorIllegalArgumentsException(){
    boolean exceptionThrown = false;
    try{
        Things thingsBadParams = new Things(5, new int[]{4,3,2}, new int[]{7,8});
    }
    catch (IllegalArgumentException e){
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
}
}

我知道也许这不是处理异常的最佳方式,但这不是重点。我可能尝试了所有解决方案(使用@Rule,@ Test(期望= IllegalArgumentException.class),并且每次测试失败时,下面都会出现一个红色栏和描述:

java.lang.IllegalArgumentException: Amount of things different than weights or values length

at pl.dsdev.Things.<init>(Things.java:14)
at ThingsTest.<init>(ThingsTest.java:11) 

我正在使用IntelliJ Idea 2017,Maven和JUnit 4.12。我该怎么做才能使测试成功?

2 个答案:

答案 0 :(得分:1)

您可以简单地将测试重写为:

@Test(expected = IllegalArgumentException.class)
public void testThingsConstructorIllegalArgumentsException(){
    Things thingsBadParams = new Things(5, new int[]{4,3,2}, new int[]{7,8});
}

答案 1 :(得分:0)

Okey,JB Nizet帮助我找到了我的错误,我创建了对象

Things things = new Things(5, new int[]{3,2,5,1,3,7},new int[]{2,7,1,2,4,5});

在测试方法之外,所以每次这行抛出一个异常,因为有6个元素,而不是5.谢谢大家:))