当使用ClassLoader InputStream时,二进制测试资源的内容错误。

问题描述 投票:0回答:1

我在测试资源中有一个二进制文件 src/test/resources/file.bin:

$ ls -la src/test/resources

-rw-r--r-- 1 g4s8 g4s8 5125 Apr 30 19:53 file.bin

在测试之前,我需要将内容复制到文件系统中,我使用的是 Thread.currentThread().getContextClassLoader() 来读取数据。

@Test
public void readsContent(@TempDir final Path tmp) throws Exception {
    final ClassLoader clo = Thread.currentThread().getContextClassLoader();
    final Path file = Files.createFile(tmp.resolve("file.bin"));
    try (
        final InputStream res = new BufferedInputStream(clo.getResourceAsStream("file.bin"));
        final OutputStream out = new BufferedOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE, StandardOpenOption.WRITE))
    ) {
        byte[] buf = new byte[8192];
        for (int read = res.read(buf); read >= 0; read = res.read(buf)) {
            out.write(buf, 0, read);
        }
    }
    // test code
}

但这个文件的内容比预想的要大 而且与资源文件中的内容有差异。

$ ls -la /tmp/junit18423574017636618834/

-rw-r--r-- 1 g4s8 g4s8 9350 May  1 12:22 file.bin

结果文件是 9350 字节大小,但源文件是 5125.用十六进制编辑器我调查了一下,这些文件只有前两个字节是一样的,其他数据都不一样。enter image description here

我的代码有什么问题?为什么这个文件不能用标准的方法正确地通过 ClassLoader?

java testing junit classloader binaryfiles
1个回答
0
投票

它是由启用 filtering Maven选项 遗传于父 pom.xml看来Maven设法找到并替换了二进制文件中的一些模式,IDE使用Maven来准备测试资源。

  <build>
    <resources>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>${basedir}/src/test/resources</directory>
        <filtering>true</filtering>
      </testResource>
    </testResources>
  </build>

我已经在项目的 pom.xml,现在它的工作。

<build>
  <testResources>
    <testResource>
      <directory>${basedir}/src/test/resources</directory>
      <filtering>false</filtering>
    </testResource>
  </testResources>
</build>
© www.soinside.com 2019 - 2024. All rights reserved.