Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 982
Ijaz Avatar asked Oct 27 '25 05:10

Ijaz


1 Answers

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.
like image 53
GhostCat Avatar answered Oct 29 '25 19:10

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!