Search code examples
javamockitojunit4powermockito

Call a real static method of a mocked class but modifying the parameters using powermockito


I'd like to call a real method of a mocked class, but modifying the parameters. I can't do any change in class that is being tested in order to better design, so I'm using PowerMockito to achieve it.

This is a simple example of a class that should be tested and can't be modified

public class Foo{
   public static Bravo whatever(Tango tango, Callable<File> callable, Function<File, File> func, String golf){
     
      callable.call();  // I'd like to call TestFileCallable.call() 
     
   }
}

Here is a class that test it:

@RunWith(PowerMockRunner.class)
@PrepareFortest({Foo.class})
@PowerMockIgnore("javax.management.*)
public class TestFoo{
   public void testWhatever(){
       PowerMockito.mockStatic(Foo.class);
       PowerMockito.when(Foo.whatever(Mockito.any(Tango.class), Matchers.any(), Matchers.any(), Mockito.anyString()))
          .thenAnswer(new Answer<Object>(){
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                 Object[] args = invocation.getArguments();
                 
                 Tango tango = (Tango) args[0];
                 Callable<File> callable = new TestFileCallable();
                 Function<File, File> func = (Function<File, File>) args[2];
                 String golf = (String) args[3];

                 //Until here is ok
                                
                 Object result = invocation.callRealMethod(); // How can I call the real method but with these modified params?
                 return result;
         }
  }
  
  class TestFileCallable implements Callable<File>{
      @Override
      public File call() throws Exception{
          return Mockito.mock(File.class);
      }
  }
 
}

Solution

  • PowerMockito.when(myMock.doSomething(Mockito.any(Aplha.class), Matchers.any(), Matchers.any(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean()))
        .thenAnswer(new Answer<Object>() {
               @Override
               public Object answer(InvocationOnMock invocation) throws Throwable {        Alpha alphaModified = new Alpha();
                   alphaModified.setDance("Tango");
                   invocation.getArguments()[0] = alphaModified;
                   return invocation.callRealMethod();
               }
           });