how to mock IamRequest impl class using mockito/powermockito?

142 views Asked by At

IamRequestImpl.java

public class IamRequestImpl<E> extends IamRequest {
    public IamRequestImpl(Iam iam, String s, String s1, Object o, Class aClass) {
        super(iam, s, s1, o, aClass);
    }
}

GcsHelper.java

public <T> T getServiceAccountKey(IamRequestInitializer req, Iam iam, String requestString,
            String api) throws IOException {
        IamRequestImpl<String> iamRequestImpl= new IamRequestImpl<String>(iam, HttpMethods.POST, requestString, String.class,
                ServiceAccountKey.class);
        iamRequestImpl.setKey(api);
        iamRequestImpl.setFields(SchedulerConstants.JSON_KEY_FIELDS);
        req.initializeJsonRequest(iamRequestImpl);
        return (T) request.execute();
    }

GCSHelperTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({ IamRequestImpl.class, ServiceAccountKey.class})
@Test
    public void testGetServiceAccountKeyOnSuccess() throws Exception{
        IamRequestInitializer mockIamRequestInitializer = Mockito.mock(IamRequestInitializer.class);
        IamRequestImpl<String> mockIamRequestImpl = PowerMockito.mock(IamRequestImpl.class);
        PowerMockito.whenNew(IamRequestImpl.class).withAnyArguments().thenReturn(mockIamRequestImpl);
        when(mockIamRequestImpl.setKey("apiKey")).thenReturn(mockIamRequestImpl);
        when(mockIamRequestImpl.setFields("apiKey")).thenReturn(mockIamRequestImpl);
        Mockito.doNothing().when(mockIamRequestInitializer).initializeJsonRequest(mockIamRequestImpl);
        spyGCSUtils.getServiceAccountKey(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
    }

When Running testGetServiceAccountKeyOnSuccess test case facing nullpointerException as iamRequestImpl is not mocking.

1

There are 1 answers

0
NIT-SuperUser On BEST ANSWER

try by converting Mockito.any() to specific object as follows.

spyGCSUtils.getServiceAccountKey((IamRequestInitializer)Mockito.any(), (Iam)Mockito.any(), Mockito.anyString(), Mockito.anyString());

since getServiceAccountKey(IamRequestInitializer, Iam, String, String)