【问题标题】:mocking a url connection object that is dependent on a string parameter模拟依赖于字符串参数的 url 连接对象
【发布时间】:2015-07-28 13:10:00
【问题描述】:

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

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;
    }
}

最好用一些返回代码 200 的参数或一些返回错误代码的参数来测试方法“运行”。就此而言,我认为我需要能够为 URL 类 (obj) 定义一个模拟表示,但由于这直接依赖于“城市”参数,我不确定如何将这种依赖注入到一个实例上使用模拟的 URL 类 (obj)。欢迎提出任何建议。

【问题讨论】:

    标签: java unit-testing mocking mockito


    【解决方案1】:

    一种方法是在一个新类(如一些帮助类)中拥有一个 getStringURL(String s) 方法,然后将该类注入到您的 WeatherServlceImpl 中。您可以模拟这个助手类并使 getStringURL() 返回一个模拟 URL 对象。一旦你有了它,你就可以模拟这个 URL 对象上的所有方法调用。

    【讨论】:

    • 是的,这是一个有效的想法,但这会是竞争条件的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多