javajunitstaticmockitosuppress

How to suppress/bypass a static method in a junit test?


Let's say I have the following code:

protected int returnFourtyTwo() {
    evilMethod(new Object, "");
    return 42;
}

protected static void evilMethod(Object obj, String string) {
    throw new RuntimeException("This is me being evil.");
}

What I'm trying to do is to run my returnFourtyTwo() method without throwing the runtime exception in my unit test. I've been able to use the suppress() method to bypass class constructors before just fine, but this is the first time I've had to bypass a static method (with more than one argument) in a non-static class. Unfortunately, resources on the topic are a bit scarce.


Solution

  • Your only way out is to mock the static method, as mentioned by @Dave. You can do that with PowerMock.

    See Mocking static methods with Mockito.