@Override
public Collection<Flight> getAll() {
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)))) {
Object read = ois.readObject();
List<Flight> objects = (ArrayList<Flight>) read;
return objects;
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
return new ArrayList<>();
}
}
@Test
public void testGetAll() {
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("flights.txt")))) {
Object read = ois.readObject();
expected = (ArrayList<Flight>) read;
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
Collection<Flight> actual = flightService.getAll();
assertEquals(expected, actual);
}
嗨,我在测试方面遇到严重问题。上面的代码是正确的测试方法吗?请帮我
问题来源:Stack Overflow
因此,假设您的类已获得要在构造函数中读取的文件,如下所示:
class FlightReader {
File file;
public FlightReader(File f) {
file = f;
}
// your getAll here
}
然后测试将首先使用已知数据创建自己的文件,然后读取该文件,然后验证结果是否符合预期,如下所示:
@Test
public void testGetAll() {
Flight f1 = new Flight("ACREG1", "B737");
Flight f2 = new Flight("ACREG2", "A320");
Flight f3 = new Flight("ACREG3", "B777");
List<Flight> written = new ArrayList<>(Arrays.asList(f1, f2, f3));
File tempFile = File.createTempFile("flights", "test");
// write sample data
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(tempFile))) {
oos.writeObject(written);
}
// data is written to a file, read it back using the tested code
FlightReader reader = new FlightReader(tempFile);
List<Flight> readFlights = reader.getAll();
// verify the written and read data are the same
assertThat(readFlights).contains(f1, f2, f3);
}
一些注意事项:
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。