Search code examples
javatestingclassloader

Can I "replace" a Java class from outside of a static code?


I have an application I want to test:

import foo.ExtClass;
public class App {
  public static void main(String[] args) {
     ExtClass ext = new ExtClass();
     ...
  }
}

I want to write a unit test for this application, however I do not want to use the foo.ExtClass, but use another mock implementation for the class.

Normally I would use a factory to instantiate the class according to some configuration that can be controlled in the unit test. However, in this case, I cannot modify the tested app.

I was thinking in the direction of writing a custom class loader to load the mock class instead of the real class - not sure if this is possible without any modification to the tested app, and how.


Solution

  • As an option you can use custom classloader, which will substite your class with a testing one. So basically instead of loading ExtClass from your app package, your classloader will load the same class from your testing package with the mock implementation.

    Here is an example:

    How to replace classes in a running application in java ?

    Also there is very usefull tutorial: https://zeroturnaround.com/rebellabs/reloading-objects-classes-classloaders/