【发布时间】: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目录中读取。 -
你有没有想过这个问题?我遇到了同样的问题。