This is my code:
HttpURLConnection connection = null;
URL url = new URL(AUTHORITY);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
BufferedWriter out
= new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write(requestBody);
out.close();
BufferedReader in = null;
StringBuffer response = null;
String access_token = null;
// handle response
int code = -1;
try {
code = connection.getResponseCode();
// bad response
if (code != OAuthConstants.HTTP_OK ) {
logger.error("Access token is expired " + code);
throw new RuntimeException(
"Unable to get connection to Azure Directory");
}else{
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = new StringBuffer();
String temp;
while ((temp = in.readLine()) != null) {
response.append(temp);
}
Object jResponse;
jResponse = JSONValue.parse(response.toString());
JSONObject jObject = (JSONObject) jResponse;
access_token = jObject.get("access_token").toString();
}
} catch (IOException e) {
logger.error("Problem with getting response from Azure");
e.printStackTrace();
} finally {
connection.disconnect();
in.close();
}
return access_token;
and this is the TEST CODE:
HttpURLConnection connection = Mockito.mock(HttpURLConnection.class);
URL url = PowerMockito.mock(URL.class);
PowerMockito.whenNew(URL.class).withAnyArguments() .thenReturn(url);
Mockito.when(url.openConnection()).thenReturn(conn ection);
Mockito.when(connection.getOutputStream()).thenRet urn(new ByteArrayOutputStream(100));
Mockito.when(connection.getResponseCode()).thenRet urn(200);
Mockito.when(connection.getInputStream()).thenRetu rn(new ByteArrayInputStream("TOKEN".getBytes("UTF-8")));
PowerMockito.mockStatic(Authenticate.class);
Mockito.mock(Authenticate.class);
String result = Authenticate.handleAuthRequest(Mockito.anyString() , Mockito.anyString());
Assert.assertNotNull(result);
Assert.assertEquals(result, "TOKEN");
Everything looks ok to me in both codes, however my test keeps failing during assertion:
Assert.assertNotNull(result);
Assert.assertEquals(result, "TOKEN");
..... Is it because i've written the test incorrectly or becauase there is something wrong with my code. please help !