変更されないハードコードされた URL を含む次のクラスがあります。
public class HttpClient {
private final String DOWNLOAD_URL = "http://original.url.json";
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(DOWNLOAD_URL);
return jsonLocator.openConnection();
}
}
ここで、テストで IOException を期待したいとします。私の意見では、これを行う唯一の方法は、final 変数があるため、完全なクラスをモック オブジェクトに書き直すことです。
public class HttpClientMock extends HttpClient {
private final String DOWNLOAD_URL = "http://wrong.test.url.json";
@Override
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(DOWNLOAD_URL);
URLConnection urlConnection = jsonLocator.openConnection();
return urlConnection;
}
}
しかし、これはある意味大袈裟です。元のメソッドが変更されたとしても、テスト結果は依然として肯定的である可能性があります。これは、この試みでは元のクラスを実際にテストしていないためです。
どうすればこれを適切に行うことができますか?(この 1 つのテストのためだけにフレームワークを使用したくないので、これを一般的な方法で解決するための設計上の試みはありますか?)