JUnit 异常处理不起作用
JUnit exception handling not working
我是单元测试的新手,正在尝试学习 JUnit。处理测试中的异常在我的项目中不起作用。这是我的 class:
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;
}
}
和测试class:
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)
我正在使用 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});
}
好的,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个。谢谢大家:)
我是单元测试的新手,正在尝试学习 JUnit。处理测试中的异常在我的项目中不起作用。这是我的 class:
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;
}
}
和测试class:
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)
我正在使用 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});
}
好的,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个。谢谢大家:)