Rohit Sharma Rohit Sharma - 11 months ago 78
Java Question

How to mock a static method in side a public class using Power mockito?

Hi every one I am trying to mock a static method name mapCreditInfo(UCIPin, creditAssessmentResults) which has two parameters UCIPin and creditAssessmentResults. UCIPin is String type and creditAssessmentResults is List
This method is inside a public class ResponseMapper
type as shown below:

private CreditInfo getAccountByUCI(String audiUser, String UCIPin) throws EnterpriseCustomerVerificationException {
List<CreditAssessmentResult> creditAssessmentResults = creditInfoRepository.getUCISummary(UCIPin, audiUser);
return ResponseMapper.mapCreditInfo(UCIPin, creditAssessmentResults);
}



Note: getAccountbyUCI method is called inside another public method
name executeCustomerVerification which is in the class
EnterpriseCustomerVerificationService


ResponseMapper class

public class ResponseMapper {

public static CreditInfo mapCreditInfo(String UCIPin, List<CreditAssessmentResult> creditAssessmentResults) {
CreditInfo creditInfo = new CreditInfo();

creditInfo.setUCIPin(UCIPin);

List<AccountCreditInfo> accountCreditInfos = new ArrayList<AccountCreditInfo>();
for (CreditAssessmentResult creditAssessmentResult : creditAssessmentResults) {
AccountCreditInfo accountCreditInfo = new AccountCreditInfo();
accountCreditInfo.setDelinquenctBalance(creditAssessmentResult.getPastDueAmount());
accountCreditInfo.setNonPayDisconnect(creditAssessmentResult.getNonpayDiscount());
accountCreditInfo.setPreviousAccountNumber(creditAssessmentResult.getAccountNumber());
accountCreditInfo.setUnreturnedEquipmentFlag(creditAssessmentResult.getUnreturnedEquipment());

accountCreditInfos.add(accountCreditInfo);
}
creditInfo.setAccountCreditInfo(accountCreditInfos);

return creditInfo;
}


}

I have Tried like some portion of my test class as shown below :
Test Class

@PrepareForTest( EnterpriseCustomerVerificationService.class)
@RunWith(PowerMockRunner.class)
public class EnterpriseCustomerVerificationServiceTest {

@InjectMocks
private EnterpriseCustomerVerificationService enterpriseCustormerVerificationServiceMock ;
@Test
public void executeCustomerVerificationTest() throws Exception {
List<ErrorResponse> errorResponses = getErrorResponse();
List<String> mso = new ArrayList<String>();
mso.add("a");
mso.add("b");
mso.add("c");
AddressResponse addressResponse = getAddressResponse();
String experianAuthorization = "experianAuthorization";
String UCIPin = "110019";
String auditUser = "ABC";

CreditInfo credit = getCreditInfo();
CreditCheck creditCheck = getcreditCheck();
EnterpriseCustomerVerificationService spy = PowerMockito.spy(new EnterpriseCustomerVerificationService());

PowerMockito.when(spy,PowerMockito.method(EnterpriseCustomerVerificationService.class,"executeCreditCheck",CreditCheck.class)).withArguments(Mockito.any()).thenReturn("@1");
Mockito.when(creditInfoRepository.getUCISummary("110019", "test")).thenReturn(getCreditAssessmentResultList());

PowerMockito.mockStatic(ResponseMapper.class);
Mockito.when(ResponseMapper.mapCreditInfo(UCIPin, getCreditAssessmentResultList())).thenReturn(credit);

CustomerVerification cv = spy
.executeCustomerVerification(getCustomerVerificationRequest1(),
"101");
}


My question is how to mock static mapCreditInfo method using power Mockito ?

Thanks

Answer Source

Like this ...

@RunWith(PowerMockRunner.class)
@PrepareForTest({ResponseMapper.class})
public class ATest {

    @Test
    public void testMockingStatic() {
        PowerMockito.mockStatic(ResponseMapper.class);

        // if you want to use specific argument matchers
        Mockito.when(ResponseMapper.mapCreditInfo(
            uciPin, creditAssessmentResults)
        ).thenReturn(creditInfo);

        // or if you want to match on any arguments passed into your static method ...
        Mockito.when(ResponseMapper.mapCreditInfo(
            ArgumentMatchers.anyString(), 
            ArgumentMatchers.anyList())
        ).thenReturn(creditInfo);

        // ...
    }
}

Notes:

  • @PrepareForTest prepares the class with the static methods which you want to mock
  • PowerMockito.mockStatic mocks all static methods that class
  • You can use standard Mockito when/then constructs to tell the mocked static methods what to return
  • The example above uses these dependencies:
    • org.mockito:mockito-core:2.7.19
    • org.powermock:powermock-module-junit4:1.7.0
    • org.powermock:powermock-api-mockito2:1.7.0

Update 1: based on your updated question which shows your test method ...

My example includes: @PrepareForTest({ResponseMapper.class}) your test method is not preparing ResponseMapper instead it is preparing EnterpriseCustomerVerificationService. It's like you are preparing the class which calls the class which has a static method rather than preparing the class which contains the static method.

I would strongly suggest creating a new test case - just temporarily - which looks like the one I have provided and use that to show yourself how to mock a static method and once you are comfortable with that then work that into your EnterpriseCustomerVerificationServiceTest.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download