如何为使用网络连接的类编写 jUnit 测试
2022-09-01 14:08:36
						我想知道在以下类中使用jUnit测试来测试方法“pushEvent()”的最佳方法是什么。我的问题是,私有方法“callWebsite()”总是需要连接到网络。如何避免此要求或重构我的类,以便在没有连接到网络的情况下对其进行测试?
class MyClass {
    public String pushEvent (Event event) {
        //do something here
        String url = constructURL (event); //construct the website url
        String response = callWebsite (url);
        return response;
    }
    private String callWebsite (String url) {
        try {
            URL requestURL = new URL (url);
            HttpURLConnection connection = null;
            connection = (HttpURLConnection) requestURL.openConnection ();
            String responseMessage = responseParser.getResponseMessage (connection);
            return responseMessage;
        } catch (MalformedURLException e) {
            e.printStackTrace ();
            return e.getMessage ();
        } catch (IOException e) {
            e.printStackTrace ();
            return e.getMessage ();
        }
    }
}