Created
February 19, 2019 20:16
-
-
Save wkorando/8f687e90441f3daa1ae13fa9da8db5c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @TestMethodOrder(OrderAnnotation.class) | |
| public class TestTempDir { | |
| @Test | |
| @Order(1) | |
| public void workInMethod(@TempDir Path tempPathArg) throws IOException { | |
| File temp = tempPathArg.resolve("temp.txt").toFile(); | |
| FileUtils.write(temp, "temp contents", StandardCharsets.ISO_8859_1); | |
| assertEquals("temp contents", FileUtils.readFileToString(temp, StandardCharsets.ISO_8859_1)); | |
| } | |
| @Test | |
| @Order(2) | |
| public void workWithInnerClassWorkAround(@TempDir Path tempPathArg) throws IOException { | |
| FileServiceWorkAround service = new FileServiceWorkAround(tempPathArg.resolve("temp.txt").toFile()); | |
| service.writeToFile("temp contents"); | |
| assertEquals("temp contents", service.readFromFile()); | |
| } | |
| @Test | |
| @Order(3) | |
| public void workWithInnerClass(@TempDir Path tempPathArg) throws IOException { | |
| FileService service = new FileService(tempPathArg.resolve("temp.txt").toFile()); | |
| service.writeToFile("temp contents"); | |
| assertEquals("temp contents", service.readFromFile()); | |
| } | |
| class FileService { | |
| private File file; | |
| public FileService(File file) { | |
| this.file = file; | |
| } | |
| public void writeToFile(String contents) throws IOException { | |
| if (StringUtils.isEmpty(FileUtils.readFileToString(file, StandardCharsets.ISO_8859_1))) { | |
| FileUtils.write(file, contents, StandardCharsets.ISO_8859_1); | |
| } else { | |
| throw new IOException("File isn't empty!"); | |
| } | |
| } | |
| public String readFromFile() throws IOException { | |
| return FileUtils.readFileToString(file, StandardCharsets.ISO_8859_1); | |
| } | |
| } | |
| class FileServiceWorkAround { | |
| private File file; | |
| public FileServiceWorkAround(File file) { | |
| this.file = file; | |
| try { | |
| FileUtils.write(file, "", StandardCharsets.ISO_8859_1); | |
| } catch (IOException e) { | |
| // TODO Auto-generated catch block | |
| e.printStackTrace(); | |
| } | |
| } | |
| public void writeToFile(String contents) throws IOException { | |
| if (StringUtils.isEmpty(FileUtils.readFileToString(file, StandardCharsets.ISO_8859_1))) { | |
| FileUtils.write(file, contents, StandardCharsets.ISO_8859_1); | |
| } else { | |
| throw new IOException("File isn't empty!"); | |
| } | |
| } | |
| public String readFromFile() throws IOException { | |
| return FileUtils.readFileToString(file, StandardCharsets.ISO_8859_1); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment