A newcomer to the world of mocks. Wondering how I could test the following method by the use of a mock object (mockito, preferrably, since I'm starting off on it)
public class WeatherServiceImpl implements IWeatherService {
private static final Logger LOGGER=LoggerFactory.getLogger(WeatherServiceImpl.class);
@Override
public String getWeatherDataFromWeb(String cityName){
return run(cityName);
}
public String run(String city){
long threadId=Thread.currentThread().getId();
String myId=String.format(" (Thread ID: %d)",threadId);
LOGGER.info(" ");
//System.out.println("\n Initializing...");
LOGGER.info(" 1.============Initializing...============"+myId);
//format the string so that all 'space' characters are replaced by '%20'
String cityFormatted=city.replaceAll(/\s+/,"%20")
//HTTP Get Request
String url="http://ift.tt/1jfvxJq"+cityFormatted;
URL obj=new URL(url);
LOGGER.info(" 2.>>>>>>>>>>>> OPENING Conn."+myId)
URLConnection conn=(HttpURLConnection) obj.openConnection();
LOGGER.info(" 3.<<<<<<<<<<<< CONN. OPENED."+myId)
//use GET
conn.setRequestMethod("GET");
//Get response code
LOGGER.info(" 4.---> Sending 'GET' request to URL: "+url+myId);
int responseCode=conn.getResponseCode();
LOGGER.info(" 5.<--- Got Response Code: "+responseCode+myId);
StringBuffer response = new StringBuffer();
//Check for validity of responseCode
if(responseCode==200)
{
BufferedReader inn = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = inn.readLine()) != null) {
response.append(inputLine);
}
inn.close();
}
else {
response.append("ERROR:$responseCode");
}
//System.out.println("\n Done.");
LOGGER.info(" 6.============ Done.============"+myId);
LOGGER.info(" ");
return response;
}
}
It would be nice to test the method 'run', with some arguments that return code 200, or some arguments that return an error code. For that matter, I think I need to be able to define a mock representation for the URL class (obj), but since this is directly dependent on the 'city' parameter, I'm not sure how to inject this dependency on an instance of the URL class (obj) using mock. Any suggestion is welcome.
Aucun commentaire:
Enregistrer un commentaire