テストファイルの入力には、Javaでストリーム

サミルAllahverdiyev:
@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);
}

こんにちは、私はテストの深刻な問題を抱えています。上記のコードは、テストへの正しい方法は何ですか?私を助けてください

料理:

したがって、このように、あなたのクラスはコンストラクタで読み込むファイルを与えていると言います。

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あなただけを返す場合はCollection、最後に?
  • あなたはすべてのJavaのシリアライズを使用しないでください。これは、セキュリティ上のリスクエラーが発生しやすいです、とJavaアーキテクトのミスと考えます。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=282647&siteId=1