Home > Enterprise >  Mockito - Mock external util method call
Mockito - Mock external util method call

Time:03-10

I'm trying to test a method that calls an external util static method for a check, and need to somehow mock it to return true / false conditions, here is a sample:

class foo {
 public void methodToTest(){
  ..logic
  boolean myCondition = SomeUtil.checkCondition(args);
  ..more logic
 }
}

Is this possible to do with mockito only? If not directly, is there a way to replace the SameUtil method with reflection or something similar?

I saw people suggesting powermock, but they don't have mockito 3.x listed on their compatibility chart, is there a better option?

This seems like a pretty common case, not everything should be autowired or injected.

CodePudding user response:

Option 1: factor out the static method call into a separate method and use Mockito spy:

class Foo {

    public void methodToTest(){
        checkCondition(args);
        // ....
    }

    boolean checkCondition(Object args) {
        return SomeUtil.checkCondition(args);
    }
}
class FooTest {

    @Spy
    @InjectMocks
    private Foo foo;

    @Test
    void methodToTest() {
        //...
        when(foo.checkCondition(yourArg)).thenReturn(true);
    }
}

See the Spy documentation for more details:

Option 2: factor out verification into a class:

class ArgumentVerifier {
    boolean checkArgument(Object args) {
        return SomeUtil.checkCondition(args);
    }
}
class Foo {
    private ArgumentVerifier verifier;

    public void methodToTest() {
        verifier.checkArgument(args); // mock the verifier as you normally would
        // ....
    }
}

CodePudding user response:

It is possible since Mockito 3.4.0: Mocking Static Methods With Mockito

But please be aware that:

  • injecting remains a more explicit way of expressing dependency on another object/service, especially external api
  • static helper methods rarely need to be mocked (especially if they depend only on their arguments)

This limits the number of cases where mocking a static method is the tool of choice, but it is worth having it under your belt.

  • Related