2

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.

user1744147
  • 1,099
  • 13
  • 30
  • 2
    Does this answer your question? [PowerMockito mock single static method and return object](https://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object) – akuzminykh Mar 08 '20 at 16:04

1 Answers1

0

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

michal-lipski
  • 81
  • 1
  • 7
  • I thought about injecting MyExecutor class. But it means the class that is essentially static becomes non static. – user1744147 Mar 09 '20 at 13:39
  • You are injecting an instance of a wrapper class that executes the static class code. MyExecutor class stays static with no changes. – michal-lipski Mar 10 '20 at 08:48
  • It does not matter. Your injected class is non static. Actually this solution is even more complex than making static method class non static and injecting it instead. I wonder if there is any testing framework than can mock static class without any refactoring. – user1744147 Mar 11 '20 at 01:39
  • It is a better solution from design perspective. You have more flexibility and can use dependency injection. Other soultion is to use PowerMock: https://github.com/powermock/powermock Although read the first paragraph of their readme before you decide to use it. – michal-lipski Mar 12 '20 at 06:32