模拟依赖于字符串参数的url连接对象

时间:2015-07-28 13:10:00

标签: java unit-testing mocking mockito

嘲笑世界的新人。想知道如何通过使用模拟对象来测试以下方法(mockito,最好,因为我开始使用它)

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)。欢迎提出任何建议。

1 个答案:

答案 0 :(得分:0)

一种方法是在新类(如某个帮助器类)中使用getStringURL(String s)方法,然后在WeatherServlceImpl中注入该类。您可以模拟此辅助类并使getStringURL()返回Mock URL对象。完成后,您可以模拟此URL对象上的所有方法调用。