maven - 如何让文件操作在 Jenkins 工作?

标签 maven jenkins junit

我在 JUnit 中编写了一些测试,这些测试是使用 File 和 FileWriter API 使用 Maven 构建的,这些测试在我的本地机器上运行,但当我尝试在 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?任何帮助将不胜感激!

最佳答案

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

所以添加这一行就足够了

File file = new File("output");

关于maven - 如何让文件操作在 Jenkins 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530068/

相关文章:

java - 在 tomcat 实时生产服务器上重新部署 war

java - 使用 JUnit 进行数据库单元测试

java - 在 Netbeans 中运行给定包中的所有 junit 测试?

maven - 原型(prototype)创建的 GWT maven 项目的 "Messages cannot be resolved to a type"错误

Tomcat 9 的 Maven 插件

java - Gradle 是否应该从 mavenLocal() 为每个项目制作 JAR-s 的本地副本?

java - Maven:在尝试在线之前如何配置为使用本地存在的 Artifact (~/.m2/repository)?

git - 设置 Git、Jira、Jenkins 并了解工作流程

linux - jenkins无法运行firefox : No protocol specified Error: cannot open display: :0

java - 如何使用 Mockito 测试网络错误?