简体   繁体   中英

Mocking static method in Java

Is there way to mock for unit test static method in Java without executing the method actual implementation? Actual implementation launches the process that cannot be done in unit test context.


public class MyExecutor {

    public static int execute(...) {
        Process pr = Runtime.getRuntime().exec(...)
        int status = pr.waitFor();
        return status;
    }


public MyClass {

    public void methodToUnitTest(...){

        MyExecutor.execute(...)

    }

I want to mock MyExecutor.execute and verify both its invocation and its params when unit testing MyClass.methodToUnitTest but without actual execution of this method.

I read that PowerMockito can mock static method but it does not prevent actual implementation from being executed.

Wrap the static class MyExecutor in a non-static class. Extract the methods of your new non-static class into an interface. Replace the dependencies to static class with the interface - use dependency injection to provide MyExecutor instances to MyClass :

public MyExecutorAdapter implements Executor{

  public void execute() {
     MyExecutor.execute()    //call to static code
  }

}

public MyClass {
  private Executor myExecutor;

  public MyClass(Executor myExecutor){   //MyExecutorAdapter instance can be injected here
    this.myExecutor = myExecutor;
  }  

  public void methodToUnitTest(...){
    myExecutor.execute(...)
  }
}

Now, with the interface, you can easily mock or provide a fake implementation for testing purposes. In your case, you probably need to have a mock to check if the execute method was called.

This is basically known as Adapter pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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