Java 模拟依赖于字符串参数的url连接对象
一个新来的嘲笑者。想知道如何使用mock对象来测试以下方法(最好是mockito,因为我是从它开始的)Java 模拟依赖于字符串参数的url连接对象,java,unit-testing,mocking,mockito,Java,Unit Testing,Mocking,Mockito,一个新来的嘲笑者。想知道如何使用mock对象来测试以下方法(最好是mockito,因为我是从它开始的) 公共类WeatherServiceImpl实现IWeatherService{ 专用静态最终记录器记录器=LoggerFactory.getLogger(WeatherServiceImpl.class); @凌驾 公共字符串getWeatherDataFromWeb(字符串cityName){ 返回运行(cityName); } 公共字符串运行(字符串城市){ long threadId=T
公共类WeatherServiceImpl实现IWeatherService{
专用静态最终记录器记录器=LoggerFactory.getLogger(WeatherServiceImpl.class);
@凌驾
公共字符串getWeatherDataFromWeb(字符串cityName){
返回运行(cityName);
}
公共字符串运行(字符串城市){
long threadId=Thread.currentThread().getId();
String myId=String.format(“(线程ID:%d)”,线程ID);
LOGGER.info(“”);
//System.out.println(“\n正在初始化…”);
LOGGER.info(“1.==========================================================================================”+myId);
//设置字符串格式,以便将所有“空格”字符替换为“%20”
字符串cityFormatted=city.replaceAll(/\s+/,“%20”)
//HTTP获取请求
字符串url=”http://api.openweathermap.org/data/2.5/weather?q=“+城市形式;
URL obj=新URL(URL);
LOGGER.info(“2.>>>>>>>>>>打开连接”+myId)
URLConnection conn=(HttpURLConnection)obj.openConnection();
LOGGER.info(“3.一种方法是在一个新类(像一些帮助器类)中有一个getStringURL(String s)方法,然后将该类注入到WeatherServlceImpl中。您可以模拟这个帮助器类并使getStringURL()成为返回一个模拟URL对象。一旦你有了这个对象,你就可以模拟这个URL对象上的所有方法调用。是的,这是一个有效的想法,但这是否会成为竞争条件的问题?
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;
}
}