【发布时间】:2018-10-09 05:07:06
【问题描述】:
我已经被这个问题困住了一段时间。是否可以模拟 new URL(url).openStream() 以返回 file.gz?我正在使用 spock 来尝试这样做。
public class DownloadFile {
public BufferedReader downloadGzipCsvFile(String url) throws MalformedURLException {
BufferedReader br = null;
if (UrlValidator.getInstance().isValid(url)){
try {
br = new BufferedReader(new InputStreamReader(new GZIPInputStream(new URL(url).openStream())));
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
} else{
throw new MalformedURLException("Supplied URL: " + url + " is an invalid URL");
}
return br;
}
}
测试类
class DownloadFileSpec extends Specification{
def "Should return buffered reader for url for gzip csv file"(){
given:
String url = "http://www.test.com"
DownloadFile downloadFile = new DownloadFile()
when:
BufferedReader br = downloadFile.downloadGzipCsvFile(url)
_.openStream() << new FileInputStream("../../../../resources/test_data.csv.gz")
then:
br.ready()
}
}
或者我会更好地编写一个返回流的私有方法?
【问题讨论】:
-
你为什么不建立一个服务器,并将它的 URL 传递给方法?
标签: java unit-testing groovy spock