gpt4 book ai didi

java - 如何测试任何方法调用是否抛出异常?

转载 作者:行者123 更新时间:2023-12-01 18:10:23 25 4
gpt4 key购买 nike

JUnit 4.12

我有以下实用方法:

public class StaticFieldsUtils {

public static <T> T getPublicStaticFieldByName(String name, Class<T> clazz){
for(Field f : clazz.getDeclaredFields()){
if(Modifier.isStatic(f.getModifiers()) &&
Modifier.isPublic(f.getModifiers()) &&
f.getName().equals(name))
try {
Object fieldValue = f.get(null);
if(clazz.isAssignableFrom(fieldValue.getClass()))
return (T) fieldValue;
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Invalid access to the field %s", name));
}
}
throw new IllegalArgumentException(String.format("A public field with the name %s does not exist in the class %s", name, clazz.getSimpleName()));
}

//Some other utility methods
}

现在,我需要编写测试用例来检查仅当不存在相同类型或其子类型之一的公共(public)静态字段时才会引发 IllegalArgumetnException

这是我倾向于写的内容:

public class StaticFieldsUtilsTest {

private static class StaticFieldContainer{
public static final StaticFieldContainer FIELD1 = new StaticFieldContainer();
public static final StaticFieldContainer FIELD2 = new StaticFieldContainer();
public static final StaticFieldContainer FIELD3 = new StaticFieldContainer();
public static final StaticFieldContainer FIELD4 = new StaticFieldContainer();
protected static final StaticFieldContainer FIELD5 = new StaticFieldContainer();
static final StaticFieldContainer FIELD6 = new StaticFieldContainer();
private static final StaticFieldContainer FIELD7 = new StaticFieldContainer();
public static StaticFieldContainer FIELD8 = new StaticFieldContainer();
}

@Test(expected=IllegalArgumentException.class)
public void testViolations(){
StaticFieldContainer field = StaticFieldsUtils.getPublicStaticFieldByName("FIELD5", StaticFieldContainer.class);
}

@Test(expected=IllegalArgumentException.class)
public void testViolations2(){
StaticFieldContainer field = StaticFieldsUtils.getPublicStaticFieldByName("FIELD6", StaticFieldContainer.class);
}
//ETC
}

问题是我无法可靠地将多个方法调用放入单个方法 @Test(expected=IllegalArgumentException.class) public void testViolationsX() 因为我需要检查 < strong>每个调用都会抛出异常。

问题:是否有一些JUnit功能可以避免为任何此类调用编写单个方法来检查它是否抛出?

最佳答案

使用JUnit TheoriesExpectedException 规则:

@RunWith(Theories.class)
public class StaticFieldsUtilsTest {

//your inner class with static fields


@Rule
public ExpectedException thrown = ExpectedException.none();

@DataPoint
public static String FIELD1 = "Field1";
@DataPoint
public static String FIELD2 = "Field2";

@Theory
public void testViolations(String field){
thrown.expect(IllegalArgumentException.class);
StaticFieldsUtils.getPublicStaticFieldByName(field, StaticFieldContainer.class);
}
}

如果您想应用其他名称的许多理论,我建议创建一个自定义注释和一个ParameterSupplier,如所述 here .

关于java - 如何测试任何方法调用是否抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com