5

私が書き込むバイトOutputStream(ファイル OutputStream) が同じから読み取ったものと同じであることをテストしたいと思いますInputStream

テストは次のようになります

  @Test
    public void testStreamBytes() throws PersistenceException, IOException, ClassNotFoundException {
        String uniqueId = "TestString";
        final OutputStream outStream = fileService.getOutputStream(uniqueId);
        new ObjectOutputStream(outStream).write(uniqueId.getBytes());
        final InputStream inStream = fileService.getInputStream(uniqueId);
    }

InputStreamないことに気がつきましたgetBytes()

どうすれば次のようなものをテストできますか

assertEquals(inStream.getBytes(), uniqueId.getBytes())

ありがとうございました

4

5 に答える 5

3

あなたが使用することができますByteArrayOutputStream

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = inStream.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

buffer.flush();

次を使用して確認します。

assertEquals(buffer.toByteArray(), uniqueId.getBytes());
于 2012-08-31T22:28:27.630 に答える
2

これを試してください(IOUtilsはcommons-ioです)

byte[] bytes = IOUtils.toByteArray(instream);
于 2012-08-31T22:15:53.417 に答える
1

入力ストリームから読み取り、ByteArrayOutputStream に書き込み、toByteArray()メソッドを使用してバイト配列に変換できます。

于 2012-08-31T22:27:41.910 に答える
0

PrintWriterJavaは必要なものを正確に提供しませんが、使用しているストリームをaやScanner:のようなものでラップすることができます。

new PrintWriter(outStream).print(uniqueId);
String readId = new Scanner(inStream).next();
assertEquals(uniqueId, readId);
于 2012-08-31T22:25:08.870 に答える
-1

このようなことを試してみませんか?

@Test
public void testStreamBytes()
    throws PersistenceException, IOException, ClassNotFoundException {
  final String uniqueId = "TestString";
  final byte[] written = uniqueId.getBytes();
  final byte[] read = new byte[written.length];
  try (final OutputStream outStream = fileService.getOutputStream(uniqueId)) {
    outStream.write(written);
  }
  try (final InputStream inStream = fileService.getInputStream(uniqueId)) {
    int rd = 0;
    final int n = read.length;
    while (rd <= (rd += inStream.read(read, rd, n - rd)))
      ;
  }
  assertEquals(written, read);
}
于 2012-08-31T22:29:48.127 に答える