简体   繁体   English

在运行时更改方法执行(Java)

[英]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! 感谢您的所有帮助!

Look at AspectJ . AspectJ

It provides advices , which can be used to execute some code around a method (before and after its execution), including bypassing the call to original method altogether and returning some arbirary value 它提供了一些advices ,可用于方法周围 (在执行之前和之后)执行一些代码,包括完全绕过对原始方法的调用并返回一些参考值

If you're just doing this for testing out classes, you could use a mocking framework to mock the classes on the server. 如果您只是为了测试类而这样做,则可以使用模拟框架来模拟服务器上的类。 I like Mockito . 我喜欢Mockito

您可以使用java反射api自己完成操作,也可以使用PowerMock之类的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM