How to mock static method without powermock

Viewed 107978

Is there any way we can mock the static util method while testing in JUnit?

I know Powermock can mock static calls, but I don't want to use Powermock.

Are there any alternatives?

4 Answers

You can use Mockito (since version 3.4.0) to mock static methods.

Given a class Foo:

class Foo{
  static String method() {
    return "foo";
  }
}

This is the test:

@Test
void testMethod() {
    assertEquals("foo", Foo.method());
    try (MockedStatic mocked = Mockito.mockStatic(Foo.class)) {
        mocked.when(Foo::method).thenReturn("bar");
        assertEquals("bar", Foo.method());
        mocked.verify(Foo::method);
    }
    assertEquals("foo", Foo.method());
}

This requires the dependency org.mockito:mockito-inline:3.4.0 or newer version.

I've had a lot of luck with doing something similar to what Maciej suggested in his answer above. In Java8 I like to wrap those static methods with functional interfaces to make them more straightforward to inject or mock. For example:

public class MyClass {
    private MyStaticWrapper staticWrapper;

    public MyClass(final MyStaticWrapper staticWrapper) {
        this.staticWrapper = staticWrapper;
    }

    public void main() {
        ...
        staticWrapper.doSomething();
        ...    
    }
}    

public interface MyStaticWrapper {
    default void doSomething() {
      Util.annoyingUntestableStaticFunction();
    }
}
Related