我的实际类接受URL作为输入并调用url.openStream(),这应该返回InputStream。
public static Map<String, Object> parseA(URL url) throws Exception {
byte[] readData = new byte[25*1024*1024];
// Here url.openStream() returning null
InputStream is = url.openStream();
while((readLength = is.read(readData, 0, 25*1024*1024)) != -1){
br = new BufferedReader(new InputStreamReader(new
ByteArrayInputStream(readData)));
// All CW_* strings are collected first
}
我的考试班是
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Test(enabled = true)
public void parseATest() {
File file=null;
try {
file =folder.newFile("testingData.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final URLConnection mockConnection = EasyMock.createMock(URLConnection.class);
final URLStreamHandler handler = new URLStreamHandler() {
@Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return mockConnection;
}
};
URL url=null;
try {
url = new URL("http://foo.bar", "foo.bar", 80, "", handler);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is=null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
EasyMock.expect(url.openStream()).andReturn(is).anyTimes();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// imageHeaderParser is object of actual class
imageHeaderParser.parseA(url);
} catch (IfmSwimParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这里 TemporaryFolder 用于创建临时文件。我不希望URL进入网络。它可以只是虚拟URL,当我调用url.openStream()时,它应该返回临时文件流。我提到过。
答案 0 :(得分:1)
文件可以转换为URL,只需执行以下操作:
Url testUrl = Paths.get("folder",("testingData.txt").toUri().toURL();
Map<String, Object> map = parseA(testUrl);
// assert map content
此外,如果要测试文件处理行为,则不需要任何模拟。