From 962bc1688aa40702fe1ac590060b54923243b402 Mon Sep 17 00:00:00 2001 From: Paul Kattenborn Date: Thu, 8 Feb 2024 22:57:55 +0100 Subject: [PATCH] test_lastMessage Test --- src/main/java/ClientHandler.java | 5 +++++ src/test/java/ChatServerTest.java | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/java/ClientHandler.java b/src/main/java/ClientHandler.java index e4104da..45570aa 100644 --- a/src/main/java/ClientHandler.java +++ b/src/main/java/ClientHandler.java @@ -9,6 +9,7 @@ public class ClientHandler implements Runnable { private String name; private BufferedReader fromClientReader; private PrintWriter toClientWriter; + private String lastMessage; // Constructor for ClientHandler public ClientHandler(ChatServer chatServer, Socket connectionToClient) { @@ -33,6 +34,7 @@ public class ClientHandler implements Runnable { while (message!=null) { // Broadcast the client's message to all connected clients chatServer.broadcastMessage(name + ": " + message); + lastMessage = message; message = fromClientReader.readLine(); } } @@ -64,4 +66,7 @@ public class ClientHandler implements Runnable { toClientWriter.println(message); // Send the message to the client toClientWriter.flush(); // Flush the stream } + public String getLastMessage() { + return lastMessage; + } } diff --git a/src/test/java/ChatServerTest.java b/src/test/java/ChatServerTest.java index 80b714d..4b7eb79 100644 --- a/src/test/java/ChatServerTest.java +++ b/src/test/java/ChatServerTest.java @@ -21,6 +21,24 @@ class ChatServerTest { // Assert assertNotNull(chatServer); } + @Test + public void testBroadcastMessage() { + // Arrange + ChatServer chatServer = new ChatServer(1234); + ClientHandler client1 = new ClientHandler(chatServer, null); + ClientHandler client2 = new ClientHandler(chatServer, null); + chatServer.getClients().add(client1); + chatServer.getClients().add(client2); + + // Act + chatServer.broadcastMessage("Test message"); + + // Assert + List clients = chatServer.getClients(); + for (ClientHandler client : clients) { + assertEquals("Test message", client.getLastMessage()); + } + } }