I am using the SpringRunner to run the Junit mockito test case , below is the class , i was trying to write the test case , but getting null object
public class AccountManager {
public String getToken() throws Exception {
@Autowired
RestClient restClient;
String auth = apiUserPrefix + apiUserName + BatchJobConstants.COLON + apiUserPassword;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.UTF_8));
String authHeader = BatchJobConstants.BASIC_SPACE + new String(encodedAuth);
String token= null;
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
data.add("grant_type", "client_credential");
String accManagerUrl = accManagerHost+":"+accManagerPort+"/"+accManagerResPath;
RestResponseObject responseObject = null;
try {
responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);
if (responseObject != null && responseObject.getPayload() != null && responseObject.getStatusCode() == HttpStatus.OK) {
JsonElement responseJson = (JsonElement) responseObject.getPayload();
if (responseJson.isJsonObject()) {
token= responseJson.getAsJsonObject().get(BatchJobConstants.ACCESS_TOKEN).getAsString();
}catch(RunTimeException e) {
//e
}
return token;
}
//Junit test case
@RunWith(SpringRunner.class)
public class AccountManagerTest {
@InjectMocks
AccountManager accountManager;
@Mock
RestClient restClient;
@Test
public void getTokenAccMgrSucess() throws Exception {
RestResponseObject restResponseObject = Mockito.mock(RestResponseObject.class);
Mockito.when(restClient.execute(Mockito.anyString(), Mockito.any(HttpMethod.class),
Mockito.anyString(), Mockito.eq(String.class), Mockito.anyString())).thenReturn(restResponseObject);
String token = accountManagerTokenProvider.getToken();
Assert.assertEquals("Token value {} ", null, token);
}
}
But still the below code return null value even after mocking this, can you please help how to mock this.
responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);
Note: Only Mockito needs to use no powermockito
Finally worked with mockito only just user any() instead of anyString(), since the Object is not matching with string only
Mockito.when(restClient.execute(Mockito.any(), Mockito.any(HttpMethod.class),
Mockito.any(), Mockito.eq(String.class), Mockito.any())).thenReturn(restResponseObject);