Vijay Krishna
Vijay Krishna

Reputation: 112

Stubbing for final Class method from another Public Class in Junit and Mockito

I Need to Stub the Final Class method in other public class method. My scenario, I have a Class name ElasticIntegration which is Public class. There is a method called licenseCheckOut

public Response licenseCheckOut(String jsonObj) {
    LogResource logData = new LogResource();
    try {
        LicenseServiceImpl licenseCheck = new LicenseServiceImpl();
        JSONObject queryObj = new JSONObject(jsonObj);
        int licenseId = -1;         
        Properties configProperties = Utilities.getConfigProperties();      
        Utilities.verifykeycloakToken(queryObj, configProperties);
        String userName = userAuth.getUserInfo(queryObj,configProperties);
        if(userName !=null){
            licenseId = licenseCheck.checkoutLicense(userName);
        }
        String result = "{\"licenseid\": "+ licenseId +"}";
        return Response.ok(result).build();
    } catch (Exception ex) {
        LogDetail details = Utilities.constructDetails("licenseCheckOut", ex);
        logData.writeLogMessage(null, details);
        return Response.serverError().entity(details).build();
    }
}

Within licenseCheckOut method there is verifykeycloakToken is the method which we need to stub. Utilities class is the final class.

 **verifykeycloakToken Function in Utilities class**

If you check with the Above Image reference exactly connection.connect() we are getting the error. So I stubbed class with when().thenReturn()

    Utilities util = new Utilities();
    Utilities mock = mock(Utilities.class);
    JSONObject queryObj = new JSONObject(jsonObj);
    Properties mapProperties = null ;
    when(mock.verifykeycloakToken(queryObj, mapProperties)).thenReturn(true);

Error I am getting here is

org.mockito.exceptions.base.MockitoException: Cannot mock/spy class com.project.Utilities Mockito cannot mock/spy because : - final class at ElasticIntegrationTest.licenseCheckOut_verifykeycloakToken_ShouldReturnSuccessBuild(ElasticIntegrationTest.java:51)

Upvotes: 1

Views: 526

Answers (1)

Shanu Gupta
Shanu Gupta

Reputation: 3807

Your verifykeycloakToken method in Utilitiesclass is a static method.

To mock this you can explore following options:

  • Mock everything inside verifykeycloakToken function. That seems little difficult to do in your case as you are creating new URL() object inside it, which mockito can't handle.
  • Use powermockito because mocktio alone can't handle the static mocking.

PS: Using powermock is generally frowned upon especially if you are following TDD. But it really comes into rescue while working with legacy code.

Upvotes: 1

Related Questions