From 5cac883023ea3cbc7e52c11c74013df3e4905695 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Tue, 2 May 2023 23:31:35 +0200 Subject: [PATCH] [BAEL-6436_printQuotesAroundString] Print "" Quotes Around a String in Java (#13925) --- .../PrintQuotesAroundAStringUnitTest.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java new file mode 100644 index 0000000000..fd4ade1ef3 --- /dev/null +++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.stringwithquotes; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class PrintQuotesAroundAStringUnitTest { + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final PrintStream originalOut = System.out; + + @BeforeEach + void replaceOut() { + System.setOut(new PrintStream(outContent)); + } + + @AfterEach + void restoreOut() { + System.setOut(originalOut); + } + + @Test + void whenWrappingAStringWithEscapedQuote_thenGetExpectedResult() { + String theySay = "All Java programmers are cute!"; + String quoted = "\"" + theySay + "\""; + + System.out.println(quoted); + + //assertion + String expected = "\"All Java programmers are cute!\"\n"; + assertEquals(expected, outContent.toString()); + } + + @Test + void whenCallingReplaceAll_thenGetExpectedResult() { + String theySay = "Can you write Java code?"; + String quoted = theySay.replaceAll("^|$", "\""); + + System.out.println(quoted); + + //assertion + String expected = "\"Can you write Java code?\"\n"; + assertEquals(expected, outContent.toString()); + } + + @Test + void whenWrappingAStringWithQuoteChar_thenGetExpectedResult() { + String weSay = "Yes, we can write beautiful Java codes!"; + String quoted = '"' + weSay + '"'; + System.out.println(quoted); + + //assertion + String expected = "\"Yes, we can write beautiful Java codes!\"\n"; + assertEquals(expected, outContent.toString()); + } +} \ No newline at end of file