Skip to content

Instantly share code, notes, and snippets.

@rponte
Created November 19, 2024 17:41
Show Gist options
  • Save rponte/f30bdd4c26a6e44caaa4ace6c17f9169 to your computer and use it in GitHub Desktop.
Save rponte/f30bdd4c26a6e44caaa4ace6c17f9169 to your computer and use it in GitHub Desktop.
Helper class to create temp files inside application classpath during the unit tests with Java and jUnit
package base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Class responsible for creating temporary files inside aplication classpath
*/
public class TempClasspathDirCreator {
private static final Logger LOGGER = LoggerFactory.getLogger(TempClasspathDirCreator.class);
private final Class<?> testClass;
public TempClasspathDirCreator(Object testClassInstance) {
this.testClass = testClassInstance.getClass();
}
/**
* Creates a temporaty file in the application classpath
*/
public TempClasspathFile createTempFile(String filename) throws IOException {
Path classpathDir = new File(
this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
).toPath();
Path testClassDir = classpathDir.resolve(".temp").resolve(testClass.getSimpleName());
Files.createDirectories(testClassDir);
Path tempfile = Files.createTempFile(
testClassDir, filename, ".tmp"
); // .temp/testClassName/filename.tmp
LOGGER.info("Temporary file created in the classpath base directory: " + tempfile);
return new TempClasspathFile(tempfile, classpathDir);
}
public static class TempClasspathFile {
private final Path filePath;
private final Path baseDir;
TempClasspathFile(Path file, Path baseDir) {
this.filePath = file;
this.baseDir = baseDir;
}
public Path getFilePath() {
return filePath;
}
/**
* Returns the relative path from the application classpath
*/
public String getRelativePath() {
return baseDir.relativize(filePath).toString();
}
public void delete() {
this.filePath.toFile().delete();
}
public void write(String content) throws IOException {
try (FileWriter writer = new FileWriter(filePath.toFile())) {
writer.write(content);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment