我有一个获取 GenericFile 作为输入参数的类,它读取数据并进行一些额外的处理。我需要测试它:
public class RealCardParser {
public static final Logger l = LoggerFactory.getLogger(RealCardParser.class);
@Handler
public ArrayList<String> handle(GenericFile genericFile) throws IOException {
ArrayList<String> strings = new ArrayList<String>();
FileInputStream fstream = new FileInputStream((File) genericFile.getFile());
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = br.readLine();//skip header
while ((strLine = br.readLine()) != null) {
l.info("handling in parser: {}", strLine);
strings.add(strLine);
}
br.close();
return strings;
}
}
问题在于新的 FileInputStream。我可以模拟 GenericFile 但它没有用,因为 FileInputStream 检查文件是否存在。我改变了我的班级:
public class RealCardParser {
public static final Logger l = LoggerFactory.getLogger(RealCardParser.class);
protected BufferedReader getBufferedReader(GenericFile genericFile) throws FileNotFoundException {
FileInputStream fstream = new FileInputStream((File) genericFile.getFile());
DataInputStream in = new DataInputStream(fstream);
return new BufferedReader(new InputStreamReader(in));
}
@Handler
public ArrayList<String> handle(GenericFile genericFile) throws IOException {
ArrayList<String> strings = new ArrayList<String>();
BufferedReader br = getBufferedReader(genericFile);
String strLine = br.readLine();//skip header
while ((strLine = br.readLine()) != null) {
l.info("handling in parser: {}", strLine);
strings.add(strLine);
}
br.close();
return strings;
}
}
所以现在我可以覆盖方法 getBufferedReader 和测试方法处理程序:
@RunWith(MockitoJUnitRunner.class)
public class RealCardParserTest {
RealCardParser parser;
@Mock
GenericFile genericFile;
@Mock
BufferedReader bufferedReader;
@Mock
File file;
@Before
public void setUp() throws Exception {
parser = new RealCardParser() {
@Override
public BufferedReader getBufferedReader(GenericFile genericFile) throws FileNotFoundException {
return bufferedReader;
}
};
when(genericFile.getFile()).thenReturn(file);
when(bufferedReader.readLine()).thenReturn("header").thenReturn("1,2,3").thenReturn(null);
}
@Test
public void testParser() throws Exception {
parser.handle(genericFile);
//do some asserts
}
}
Handler 方法现在已经覆盖了测试,但我仍然发现了导致 cobertura 问题的方法 getBufferedReader。如何测试方法 getBufferedReader 或者问题的另一种解决方案?