Search code examples
javaunit-testingjunitmockito

Test a method with mockito, which uses some utility methods of some other class


I have a method which receive a message of from a queue and I need to write the unit test for this method with Mockito. The method uses a utility class UtilClass. I am confused about how to write the unit test for this method

public boolean findSomeRecord(Message<?> message){
    Details details = UtilClass.getHeaderValue(Constants.DETAILS, message, Details.class);

    Record record = recordService.findById(details.getDetailsId());

    if(record == null ){
        return false;
    }
    return true;
}

Solution

  • The answer: it depends.

    I guess your first problem is that this static method call UtilClass.getHeaderValue() doesn't function correctly in your unit test?

    You see, because if it would function ... what would you care about it? Meaning: you want to test that findSomeRecord() returns either true or false. So, in a perfect setup, you would only have two tests like:

    assertThat(objectUnderTest.findSomeRecord(someRecordThatCanBeFound), is(true));
    

    resp.

    assertThat(objectUnderTest.findSomeRecord(someRecordThatCanNotBeFound), is(false));
    

    But probably that static method doesn't work that way in your unit test setup. Then you have two choices:

    1. You turn to PowerMock(ito); which allows you to mock static methods
    2. You change your design; for example by giving up on the idea that this util method is a static method. Because when you are not calling a static method, you can (almost) always use dependency injection to give your production code a mocked object to to call its methods on.