使用反射来识别抛出的错误是否与预期错误匹配



我需要编写一个简单的代码测试程序,但是在比较给定的错误类和测试期望的类时遇到了困难。我应该在这个练习中使用反射。

我有我的代码测试类:
public class TestRunner {
private String result = "";
public void runTests(List<String> testClassNames) {
for (String testClassName : testClassNames) {
Class<?> clazz;
try {
clazz = Class.forName(testClassName);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("No such class.");
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.getAnnotation(MyTest.class) != null) {
if (testClassName.equals("reflection.tester.ExampleTests1")) {
result += method.getName() + "() - ";
ExampleTests1 instance = new ExampleTests1();
try {
// if null, result = OK
method.invoke(instance);
result += "OKn";
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
// if error is caught result = FAILED
result += "FAILEDn";
}
} else {
// the second class. should only return "OK" if the error is implemented from the exception class
result += method.getName() + "() - ";
ExampleTests2 instance = new ExampleTests2();
try {
method.invoke(instance);
result += "FAILEDn";
} catch (RuntimeException e) {
Throwable original = e.getCause();
Object expected = method.getReturnType();
if (original.getClass().isAssignableFrom(expected.getClass())) {
result += "OKn";
} else {
result += "FAILEDn";
}
} catch (InvocationTargetException | IllegalAccessException e) {
result += "ERRORn";
}
}
}
}
}
}
}

也有两个测试类。在第一个测试中,只有一个规则,如果测试不会抛出异常,测试应该通过,并且它正在工作。第二类更为复杂。如果抛出的错误类被实现,或者与预期的错误类相同,那么测试应该通过,结果中应该添加OK。目前,我的代码根本不会捕获RunTimeException,而是移动到最后一个捕获块。我该如何解决这个问题?

我还将添加测试类以获得更多信息。

public class ExampleTests2 {
@MyTest(expected = RuntimeException.class)
public void test3() {
throw new IllegalStateException();
}
@MyTest(expected = IllegalStateException.class)
public void test4() {
throw new RuntimeException();
}
@MyTest(expected = IllegalStateException.class)
public void test5() {
throw new IllegalStateException();
}
@MyTest(expected = IllegalStateException.class)
public void test6() {
}
public void helperMethod() {
}

}

test3()和test5()应该通过,test4()和test6()应该失败,helperMethod()不会被检查,因为我只需要使用带有@MyTest注释的测试。

JUnit有一个assertThrows方法来检查是否抛出了异常。它有一个方法签名

static <T extends Throwable> assertThrows​(Class<T> expectedType, Executable executable){}

文档如下:https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertThrows(java.lang.Class,org.junit.jupiter.api.function.Executable)

,下面是JUnit如何实现它的:https://github.com/junit-team/junit5/blob/main/junit-jupiter-api/src/main/java/org/junit/jupiter/api/AssertThrows.java

最新更新