From d45bf1962212123a28a4420b4f348b20539d15a8 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Sat, 3 Feb 2024 19:17:45 +0530 Subject: [PATCH] Add unit tests --- .../systemin/SystemInReadUnitTest.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 core-java-modules/core-java-console/src/test/java/com/baeldung/systemin/SystemInReadUnitTest.java diff --git a/core-java-modules/core-java-console/src/test/java/com/baeldung/systemin/SystemInReadUnitTest.java b/core-java-modules/core-java-console/src/test/java/com/baeldung/systemin/SystemInReadUnitTest.java new file mode 100644 index 0000000000..0a04b76a47 --- /dev/null +++ b/core-java-modules/core-java-console/src/test/java/com/baeldung/systemin/SystemInReadUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.systemin; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.jupiter.api.Test; + +public class SystemInReadUnitTest { + @Test + void givenUserInput_whenUsingReadMultipleCharacters_thenRead() { + System.setIn(new ByteArrayInputStream("Hello\n".getBytes())); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outputStream)); + SystemInRead.readMultipleCharacters(); + + assertEquals("Enter characters (Press 'Enter' to quit):\n" + "Hello", outputStream.toString().trim()); + } + + @Test + void givenUserInput_whenUsingReadSingleCharacter_thenRead() { + System.setIn(new ByteArrayInputStream("A".getBytes())); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outputStream)); + SystemInRead.readSingleCharacter(); + + assertEquals("Enter a character:\nA", outputStream.toString().trim()); + } + + @Test + void givenUserInput_whenUsingReadSingleCharacter_thenReading() { + System.setIn(new ByteArrayInputStream("ABC".getBytes())); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outputStream)); + SystemInRead.readWithParameters(); + + assertEquals("Data read: ABC\n" + "Bytes Read: 3", outputStream.toString().trim()); + } +}