【问题标题】:How to get File manipulation to work in Jenkins?如何让文件操作在 Jenkins 中工作?
【发布时间】:2018-03-13 19:02:35
【问题描述】:

我在使用 File 和 FileWriter API 的 Maven 构建的 JUnit 中编写了一些测试,这些测试在我的本地机器上运行,但当我尝试在 Jenkins 中构建它时却不行。为了让我的测试在 Jenkins 中运行,我必须遵循一个特殊的约定吗?

在我的测试文件中,我正在初始化我的资源文件夹所在的一些路径:

  private String resourcesFolderPath = new File("src/test/resources").getAbsolutePath();
  private String outputFolderPath = resourcesFolderPath + "/output";
  private File outputFolder = new File(outputFolderPath);

这是一个在 Jenkins 中失败的测试:

@Test
public void test() throws Exception {
    File file = new File(outputFolder.list()[0]); // File not found exception at this line
    if (!file.exists()) file.mkdirs(); // I added this line after Jenkins build failed, did not fix the problem
    String fileListName = file.getName();

    FileReader fileReader = new FileReader(outputFolderPath + "/" + fileListName);
    BufferedReader buffReader = new BufferedReader(fileReader);

    String firstFileName = buffReader.readLine();

    assertTrue(firstFileName.contains("test1.txt"));

    buffReader.close();
  }

输出文件夹包含我要测试的文件,但 Jenkins 失败并出现 FileNotFoundException:

java.io.FileNotFoundException: /home/jenkins/workspace/utils-feature-branches-ci/file-list/src/test/resources/output/File_List.txt (No such file or directory)

奇怪的是,当使用 Maven 构建时,这个测试在我的本地机器上工作,但在 Jenkins 上却不行。所以我的问题是如何修改我的代码以便这个测试与 Jenkins 一起工作?任何帮助将不胜感激!

【问题讨论】:

  • 如果你想从资源文件夹中读取一些东西,你必须通过getClass().getResourcesAsStream("/whatever.properties")。像您一样阅读目录列表是您做出的一个假设。文件的顺序...文件的顺序取决于 OS/JDK,因此您不必假设您将获得文件名的顺序。此外,不要使用文件名从src/test/resources 目录中读取。
  • 你有没有想过这个问题?我遇到了同样的问题。

标签: maven jenkins junit


【解决方案1】:

通过 JUnit 运行测试类时,src/test/resources 将是您的类路径。

所以添加这一行就足以满足您的目的

File file = new File("output");

【讨论】:

  • 谢谢,但我的问题并不是关于 JUnit,我的输出路径已经可以工作了,但它在 Jenkins 上不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 2016-01-08
相关资源
最近更新 更多