Ignoring a call to an internal static call

public static ResponseBean call(Bean bean) throws Exception {
    // statements...
    IgnoreCall.ignoreMethodCall(bean);
    // statements...

    // return
}

Using the code snippet above, you can test a method that ignores a call IgnoreCall.ignoreMethod(Bean)without having to place the entire statement under a logical condition?

Here's the unit test code snippet:

@RunWith(PowerMockRunner.class)
@PrepareTest
public ClassHelperTest {

    @Test
    public void testCall() throws Excpetion {
        // stubbing...
        ResponseBean responseBean = ClassHelper.call(bean);
        // verify/ies
        // assert/s
    }

}

Notes:

  • Refactoring should be avoided ClassHelper.call(Bean). Even with poor design, OO refactoring is expensive.
  • The signature of the method is blocked unless another template is used for replacement.
  • I tried to use Mockito.whenit PowerMockito.whenin the target static method, while debugging was not performed.
+4
source share
1 answer

, , "" - PowerMock; .

IgnoreCall ; ignoreMethodCall() no-op.

: , void. , .

, :

  • , , .

void . , , .

: PowerMock "" - ; "" ! , PowerMock , , void "".

, , . when() Mockito . , : , .

; [mcve] , :

package ghostcat.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class IgnoreCall {
  public static void ignoreMethodCall(Object o) {
    System.out.println("SHOULD NOT SHOW UP: " + o);
  }
}

class CuT {
  public static Object call(Object bean) {
    System.out.println("statement1");
    IgnoreCall.ignoreMethodCall(bean);
    System.out.println("statement2");
    return "whatever";
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(IgnoreCall.class)
public class PMTest {
  @Test
  public void test() {
    PowerMockito.mockStatic(IgnoreCall.class);
    CuT.call("yeha");
  }
}

... IgnoreCall; , "".

:

statement1
statement2

//      PowerMockito.mockStatic(IgnoreCall.class);

:

statement1
SHOULD NOT SHOW UP: yeha
statement2

, , , .

eclipse neon, IBM java8 JDK JAR powermock-mockito-junit-1.6.6.zip .

+5

Source: https://habr.com/ru/post/1663068/


All Articles