基于Brett Walker对此的评论question ,我想知道如何做到这一点。
“如果您想让单元测试失败,从最一般的意义上来说,当此方法中的代码执行 catch 子句时,您将必须检测字节代码来告诉您 catch 子句何时被执行。正在执行。这是一项复杂的任务。我不推荐这样做。”
我如何测试某个方法是否已执行 catch 子句? (下面示例中的 isCatched()
。
假设我有以下类(class):
public class A {
public void method() {
try {
// some code that may or may not throw an exception
} catch(Exception e) {
// do nothing
}
}
}
然后在其他地方:
public class CatchTester {
private A a;
public CatchTester(A a) {
this.a = a;
}
public boolean isCatched() {
// how to do this?
}
}
最佳答案
有两种方法,都需要了解如何操作 Java 字节代码。工具如ASM存在是为了使操作字节码更容易一些。然后输入 Java Agent或者编写一个自定义类加载器,在将类字节加载到 JVM 时修改它们。
这种方法的一个很好的例子是 https://github.com/google/allocation-instrumenter 。 Allocation-Instrumenter 修改类的字节码,以便可以注册一个回调方法,在发生对象分配时调用该方法。想象一个用于 try/catch 工具的类似库并不难。
关于java - 如何检测字节码来判断 catch 子句何时被执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30621542/