模拟世界的新手。想知道如何通过使用模拟对象(最好是模拟对象,因为我是从它开始的)来测试以下方法
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://api.openweathermap.org/data/2.5/weather?q="+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;
}
}
这将是很好的测试方法'run',与一些参数返回代码200,或一些参数返回错误代码。为此,我认为我需要能够为URL类(obj)定义模拟表示,但由于这直接依赖于"city"参数,因此我不确定如何使用mock将此依赖项注入URL类(obj)的实例。
一种方法是在新类(如某些helper类)中使用getStringURL(String s)方法,然后将该类注入到WeatherServlceImpl中。您可以模拟这个助手类,并使getStringURL()返回一个mock URL对象。一旦有了这个,就可以模拟这个URL对象上的所有方法调用。