我已经学会了如何在Junit测试中捕获异常。但是现在我想循环遍历可能导致异常的参数,{null, Object.class}
当前测试针对第一个循环运行,然后通过并存在,并且不检查下一个循环参数。
@Rule
public ExpectedException ee;
public ClassTest() {
this.ee = ExpectedException.none();
}
/**
* Test of isCompramised method.
*/
@Test
public void testIsCompramised2() {
System.out.println("isCompramised Exception");
Class<?>[] c = {null, Object.class};
for (Class<?> class1 : c) {
MyClass instance = new MyClass();
ee.expect(IllegalArgumentException.class);
boolean result = instance.isCompramised(class1);
fail("Exception should have been thrown");
}
}
所以我尝试了这一点,它完成了for循环,但是所有预期的异常都失败了,因为我认为Try Catch现在可以窃取该异常。
/**
* Test of isCompramised method, of class MyClass.
*/
@Test
public void testIsCompramised2() {
System.out.println("isCompramised Exception");
Class<?>[] c = {null, Object.class};
for (Class<?> class1 : c) {
MyClass instance = new MyClass();
try{
ee.expect(IllegalArgumentException.class);
boolean result = instance.isCompramised(class1);
fail("Exception should have been thrown");
} catch (Exception e){
continue;
}
}
}
有什么建议吗?
这样对吗?
try{
boolean result = instance.isCompramised(class1);
fail("Exception should have been thrown");
} catch (Exception e){
AssertTrue(e instanceOf IllegalArgumentException);
continue;
}
我会喜欢这样的东西:
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
@RunWith(Parameterized.class)
public class Foo {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Parameter
public Class<?> input;
/**
* Test of isCompramised method, of class MyClass.
*/
@Test
public void testIsCompramised() {
this.expectedException.expect(IllegalArgumentException.class);
final MyClass instance = new MyClass();
instance.isCompramised(input);
}
@Parameters(name = "test for {0}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { {null}, {Object.class} });
}
}
(或两种测试方法,一种用于null
,一种用于Object
)
编辑:一些补充(请参阅注释)
带注解的方法@Parameters
返回Iterable
包含Object[]
。每个字段Object[]
都绑定到一个带@Parameter
注释的字段(使用@Parameter
as的值作为索引[默认值:0])。JUnit运行器Parameterized
将遍历@Parameters
数据,并为每个数组设置字段值,然后运行该类中的每个测试。
另请参见:Parameterized
javadoc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句