Skip to content

Add error message to TemporaryFolder.newFolder("String/String") #959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/main/java/org/junit/rules/TemporaryFolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,30 @@ public File newFolder(String... folderNames) throws IOException {
File file = getRoot();
for (int i = 0; i < folderNames.length; i++) {
String folderName = folderNames[i];
validateIOSeparator(folderName);
file = new File(file, folderName);
if (!file.mkdir() && isLastElementInArray(i, folderNames)) {
throw new IOException(
"a folder with the name \'" + folderName + "\' already exists");
throw new IOException("a folder with the name \'" + folderName + "\' already exists");
}
}
return file;
}

/**
* Validates if a OS separator was used in the attempt to create a folder structure.
*
* @param folderName
* String passed as the temp folder name
*/
private void validateIOSeparator(String folderName) throws IOException {
if (folderName.contains(File.separator)) {
String errorMsg = "It's not possible to use the OS separator to create folder " +
"hierarchies like 'MyParentFolder'%s'MyFolder'. Please use newFolder('MyParentFolder', "+
"'MyFolder') instead";
throw new IOException(String.format(errorMsg,File.separator));
}
}

private boolean isLastElementInArray(int index, String[] array) {
return index == array.length - 1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,19 @@ public void canSetTheBaseFileForATemporaryFolder() throws IOException {
assertThat(tempDir, is(folder.getRoot().getParentFile()));
}

@Test
public void fileSeparatorShouldThrowExceptionWhenUsedAsPartOfFolderNameParameter() throws IOException {
tempFolder.create();

thrown.expect(IOException.class);
String errorMsg = "It's not possible to use the OS separator to create folder " +
"hierarchies like 'MyParentFolder'%s'MyFolder'. Please use newFolder('MyParentFolder', "+
"'MyFolder') instead";
thrown.expectMessage(String.format(errorMsg,File.separator));
tempFolder.newFolder("MyParentFolder" + File.separator + "MyFolder");

}

private File createTemporaryFolder() throws IOException {
File tempDir = File.createTempFile("junit", "tempFolder");
assertTrue("Unable to delete temporary file", tempDir.delete());
Expand Down