调用模拟类的真正静态方法,但使用 powermockito 修改参数

问题描述 投票:0回答:1

我想调用模拟类的真实方法,但修改参数。为了更好的设计,我无法对正在测试的类进行任何更改,因此我使用 PowerMockito 来实现它。

这是一个应该测试且不能修改的类的简单示例

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() 
     
   }
}

这是一个测试它的类:

@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);
      }
  }
 
}
java mockito junit4 powermockito
1个回答
0
投票
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();
           }
       });
© www.soinside.com 2019 - 2024. All rights reserved.