From da57a3233feca05382ae212c1daca80474c65f4c Mon Sep 17 00:00:00 2001 From: Tobias Herbert Date: Thu, 8 Feb 2024 15:20:57 +0100 Subject: [PATCH] refactoring: Added automatic creation/deletions of test.tx in AdminTest --- src/test/java/org/example/AdminTest.java | 35 ++++++++++++++++-------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/test/java/org/example/AdminTest.java b/src/test/java/org/example/AdminTest.java index a863a79..d9b7c80 100644 --- a/src/test/java/org/example/AdminTest.java +++ b/src/test/java/org/example/AdminTest.java @@ -1,5 +1,7 @@ package org.example; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.*; @@ -10,6 +12,23 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.*; class AdminTest { + @BeforeEach + void setup() throws IOException { + // Ensure the file is clean before each test + new PrintWriter(fileName()).close(); + } + @AfterEach + void tearDown() { + // Clean up after tests + new File(fileName()).delete(); + } + + public String fileName() + { + String filename = "testAdminData.txt"; + return filename; + } + //Tests printAdminInfo Method @org.junit.jupiter.api.Test void printAdminInfo() { @@ -31,17 +50,13 @@ class AdminTest { @Test void writeToFile() throws IOException { Admin admin = new Admin("Simon", "A1001", "Admin") ; + + admin.writeToFile(admin, fileName()); - String filename = "testAdminData.txt"; - - admin.writeToFile(admin, filename); - - Path path = Path.of(filename); + Path path = Path.of(fileName()); String content = Files.readString(path); assertEquals("Simon\nA1001\nAdmin", content); - Files.delete(path); - } //Tests readFromFile Method @Test @@ -54,8 +69,8 @@ class AdminTest { } catch (IOException e) { e.printStackTrace(); } - String filename = "testAdminData.txt"; - List testAdmins = Admin.readFromFile(filename); + + List testAdmins = Admin.readFromFile(fileName()); assertEquals(1, testAdmins.size()); Admin admin = testAdmins.get(0); @@ -64,7 +79,5 @@ class AdminTest { assertEquals("A1001", admin.getId()); assertEquals("Admin", admin.getRole()); - Files.delete(Path.of(filename)); - } } \ No newline at end of file