[英]Changing method execution in runtime (Java)
I am a Software Engineer in Test, and I am trying to write code that can replace production side method so that test can execute those instead. 我是测试部门的软件工程师,我正在尝试编写可替代生产方方法的代码,以便测试可以替代地执行这些方法。 Basically, I do not want to modify production code for testability. 基本上,我不想为了可测试性而修改生产代码。
Here is a simple scenario: 这是一个简单的场景:
public class Foo {
public static void foo() {
printA();
}
public static void printA() {
System.out.println("A");
}
public static void printB() {
System.out.println("B");
}
}
public class Foobar {
public Foobar() {
}
public void test() {
Foo.foo();
}
public static void main(String[] args) {
//Try changing the method here
new Foobar().test();
}
}
As you can see, when the main executes, it will print "A" since it calls the method printA on static method foo(). 如您所见,当main执行时,它将打印“ A”,因为它在静态方法foo()上调用了方法printA。 Now on runtime, is there a way I can inject or modify such that foo will call printB instead of printA? 现在在运行时,是否有一种方法可以注入或修改,以便foo将调用printB而不是printA?
Thank you for all the help! 感谢您的所有帮助!
您可以使用java反射api自己完成操作,也可以使用PowerMock之类的工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.