0

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(). Now on runtime, is there a way I can inject or modify such that foo will call printB instead of printA?

Thank you for all the help!

2
  • You can use Instrumentation to acquire access to class bytes, and then use ASM, BCEL, or another bytecode analysis/modification library to modify the method. Commented Feb 15, 2013 at 22:04
  • I managed to do something like that once using javassist Commented Feb 15, 2013 at 22:06

3 Answers 3

1

Look at 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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

You can do it yourself using the java reflection api, or you can you use a tool like PowerMock.

1 Comment

I don't believe reflections allow code swapping. Can you elaborate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.