Reputation: 7957
Iam trying to create a junit test case for the below functionality setUrl. How can i mock the java url class with mockito
public void setUrl(String url) {
this.url = URLUtil.processURL(url);
try {
URL dst = new URL(this.url);
InputStream is = dst.openStream();
Scanner scanner = new Scanner(is);
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine())
sb.append(scanner.nextLine()).append("\n");
if (validate(sb.toString())) {
--------
} else {
}
is.close();
scanner.close();
} catch (Exception ex) {
}
}
private boolean validate(String content) {
JSONParser parser = new JSONParser();
Boolean isJsonValid = false;
JSONObject json = null;
try {
--------
//json validation goes here
} catch (Exception e) {
}
return isJsonValid;
}
code tried
URL mockedURL = PowerMockito.mock(URL.class);
MockedHttpConnection mockedConnection = PowerMockito.mock(MockedHttpConnection.class);
PowerMockito.whenNew(URL.class).withParameterTypes(String.class).withArguments(sourceUrl).thenReturn(mockedURL);
PowerMockito.when(mockedURL.openConnection()).thenReturn(mockedConnection);
But I'm not sure whether I'm following the right way.
Upvotes: 1
Views: 213
Reputation: 140427
Two answers:
new()
, you simply have to follow the all the mandatory steps, as outlined here for example. Meaning: you need to use the @PrepareForTest annotation, and the correct runner.new()
in the first place. That makes it just harder to test your code. It forces you to rely on PowerMock(ito). And this dependency makes your life a lot harder!Meaning: it is technically possible and straight forward to mock calls to new()
, you only need to follow the recipe for that. But the better long term solution is to rework your production code so that you can test it without PowerMock(ito). For example by using some sort of dependency injection that provides some URL object to your code under test.
Upvotes: 1