Actual Output different to expected output ----- package org.example; import org.example.cmd.CmdRegister; import org.example.day.SystemDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Field; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; class CmdRegisterTest { private CmdRegister cmd; private Library library; private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); @BeforeEach public void resetInstance() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field systemDateInstance = SystemDate.class.getDeclaredField("instance"); systemDateInstance.setAccessible(true); systemDateInstance.set(null, null); Field instance = Library.class.getDeclaredField("instance"); instance.setAccessible(true); instance.set(null, null); SystemDate.createTheInstance("01-Jan-2020"); library = Library.getInstance(); Field field = library.getClass().getDeclaredField("allMembers"); field.setAccessible(true); ArrayList<Member> allMembers = (ArrayList<Member>) field.get(library); allMembers.clear(); Field field2 = library.getClass().getDeclaredField("allGears"); field2.setAccessible(true); ArrayList<Member> allGears = (ArrayList<Member>) field2.get(library); allGears.clear(); System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); } @Test public void testExecuteExMemberIDInUse() { Member m = new Member("001", "John"); cmd.execute(new String[] {"register", m.getId(), m.getName()}); String expected = """ Member ID already in use: 001 John """; assertEquals(expected, outContent.toString()); }
The CmdRegister.java is the class that handles the part of a new member. The execute functions didn't throw the ExMemberIDInUse exception. Modified class as: public void execute(String[] cmdParts) { try { if (cmdParts.length < 3) throw new ExInsufficientArguments(); String id = cmdParts[1]; String name = cmdParts[2]; m = Club.getInstance().findMember(id); if (m != null) throw new ExMemberIDInUse(m.getId(), m.getName()); m = new Member(id, name); addUndoCommand(this); clearRedoList(); System.out.println("Done."); } catch (ExInsufficientArguments e) { System.out.println(e.getMessage()); } catch (ExMemberIDInUse e) { System.out.printf("%s %s %s\n", e.getMessage(), e.getId(), e.getName()); } }