diff --git a/src/main/java/org/example/Professor.java b/src/main/java/org/example/Professor.java index 5388030..ad7b358 100644 --- a/src/main/java/org/example/Professor.java +++ b/src/main/java/org/example/Professor.java @@ -116,4 +116,20 @@ public class Professor { writer.newLine(); } } + + public static List readFromFile() throws IOException { + List professors = new ArrayList<>(); + try (BufferedReader reader = new BufferedReader(new FileReader("professorData.txt"))) { + String line; + while ((line = reader.readLine()) != null) { + // Assuming the toString format is exactly how we write to the file + String[] parts = line.replace("Professor{", "").replace("}", "").split(", "); + String professorID = parts[0].split("'")[1]; // Extracting professorID + String name = parts[1].split("'")[1]; // Extracting Name + String role = parts[2].split("'")[1]; // Extracting role + professors.add(new Professor(professorID, name, role)); + } + } + return professors; + } } diff --git a/src/test/java/org/example/ProfessorTest.java b/src/test/java/org/example/ProfessorTest.java index ab52603..65b4c2c 100644 --- a/src/test/java/org/example/ProfessorTest.java +++ b/src/test/java/org/example/ProfessorTest.java @@ -1,4 +1,48 @@ package org.example; +import org.example.Professor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import java.io.*; +import java.util.List; + + public class ProfessorTest { + + @BeforeEach + void setup() throws IOException { + // Ensure the file is clean before each test + new PrintWriter("professorData.txt").close(); + } + + @AfterEach + void tearDown() { + // Clean up after tests + new File("professorData.txt").delete(); + } + + @Test + void testWriteToFile() throws IOException { + Professor professor = new Professor("P1001", "John Doe", "Professor"); + professor.writeToFile(); + + // Verify the file contains the expected data + try (BufferedReader reader = new BufferedReader(new FileReader("professorData.txt"))) { + assertEquals("Professor{professorID='P1001', Name='John Doe', role='Professor'}", reader.readLine()); + } + } + @Test + void testReadFromFile() throws IOException { + Professor professor = new Professor("P1002", "Jane Doe", "Professor"); + professor.writeToFile(); + + List professors = Professor.readFromFile(); + + assertEquals(1, professors.size()); + assertEquals("P1002", professors.get(0).getProfessorID()); + assertEquals("Jane Doe", professors.get(0).getName()); + assertEquals("Professor", professors.get(0).getRole()); + } }