Junit 测试访问 CP 资源在 gitlab 上失败但在本地工作

Junit test accessing CP resource fails on gitlab but works locally

我正在设置 gitlab 管道,但构建失败。这很奇怪,我没有看到麻烦。 JUnit 4.12,gradle 4.8.1.

测试

public class ClientTest {
@Test
public void test() throws JAXBException, SAXException {
    String xml = ClientTest.class.getClassLoader().getResource("xml/Client.xml").getFile();
    ClientEventReq req = (ClientEventReq) unmarshaller.unmarshal(new File(xml));

我已将 build 目录保存为工件,它看起来正确且与本地计算机相同:

module/build/resources/test/xml/Client.xml

但它在 gitlab 上失败了:

java.nio.file.NoSuchFileException: builds/product/module/build/resources/test/xml/Client.xml
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.Files.readAllBytes(Files.java:3152)
at ClientTest.test(ClientModificationEventReqTest.java:41)

我添加了更多命令来识别文件所在的位置

$ pwd
/builds/product
$ ls
module
gradle
gradlew
gradlew.bat
settings.gradle
$ ls builds/product/module
ls: cannot access 'builds/product/module': No such file or directory

所以看起来当前目录是 /builds/product 但 java 想要文件 builds/product/module/build/resources/test/xml/Client.xml.

我重写了代码以使用 URL 而不是 File:

URL url = ClientModificationEventReqTest.class.getClassLoader().getResource(path);
ClientEventReq req = (ClientEventReq) unmarshaller.unmarshal(url);