开发者社区> 问答> 正文

在Java中测试文件输入流

@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

展开
收起
montos 2020-03-27 16:07:03 526 0
1 条回答
写回答
取消 提交回答
  • 因此,假设您的类已获得要在构造函数中读取的文件,如下所示:

    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);
    }
    

    一些注意事项:

    • 您应该ArrayList尽可能少地使用特定的类(在这种情况下)。ArrayList如果最后只返回a Collection,为什么要强制转换为a ?
    • 您根本不应该使用Java序列化;它容易出错,存在安全风险,并且Java架构师认为这是一个错误。 回答来源:Stack Overflow
    2020-03-27 16:07:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载