Java JUnit异常处理不工作

Java JUnit异常处理不工作,java,maven,junit,exception-handling,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!=weight

我是单元测试新手,我正在努力学习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(expected=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) 
java.lang.IllegalArgumentException:与权重或值长度不同的事物数量
位于pl.dsdev.Things.(Things.java:14)
在ThingsTest.(ThingsTest.java:11)

我正在使用IntelliJ Idea 2017、Maven和JUnit 4.12。我应该做些什么才能使测试成功?

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

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

好吧,它帮我找到了我的错误,我已经创建了对象

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

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

堆栈跟踪显示您没有执行发布的代码。异常是从ThingsTest构造函数引发的。并且在发布的代码中没有构造函数。给我们看看你的实际代码