BAEL-4341 - JUnit test for System.out.println()
This commit is contained in:
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.systemout;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOut;
|
||||
|
||||
class SystemOutPrintlnUnitTest {
|
||||
|
||||
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
|
||||
private final PrintStream standardOut = System.out;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
System.setOut(new PrintStream(outputStreamCaptor));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void tearDown() {
|
||||
System.setOut(standardOut);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSystemOutRedirection_whenInvokePrintln_thenOutputCaptorSuccess() {
|
||||
print("Hello Baeldung Readers!!");
|
||||
|
||||
Assert.assertEquals("Hello Baeldung Readers!!", outputStreamCaptor.toString()
|
||||
.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTapSystemOut_whenInvokePrintln_thenOutputIsReturnedSuccessfully() throws Exception {
|
||||
|
||||
String text = tapSystemOut(() -> {
|
||||
print("Hello Baeldung Readers!!");
|
||||
});
|
||||
|
||||
Assert.assertEquals("Hello Baeldung Readers!!", text.trim());
|
||||
}
|
||||
|
||||
private void print(String output) {
|
||||
System.out.println(output);
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.systemout;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.contrib.java.lang.system.SystemOutRule;
|
||||
|
||||
public class SystemOutPrintlnWithRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
|
||||
|
||||
@Test
|
||||
public void givenSystemOutRule_whenInvokePrintln_thenLogSuccess() {
|
||||
print("Hello Baeldung Readers!!");
|
||||
|
||||
Assert.assertEquals("Hello Baeldung Readers!!", systemOutRule.getLog()
|
||||
.trim());
|
||||
|
||||
Assert.assertEquals("Hello Baeldung Readers!!\n", systemOutRule.getLogWithNormalizedLineSeparator());
|
||||
}
|
||||
|
||||
private void print(String output) {
|
||||
System.out.println(output);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user