Install with maven
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>consolecaptor</artifactId>
<version>1.0.3</version>
<scope>test</scope>
</dependency>
testImplementation 'io.github.hakky54:consolecaptor:1.0.3'
libraryDependencies += "io.github.hakky54" % "consolecaptor" % "1.0.3" % Test
<dependency org="io.github.hakky54" name="consolecaptor" rev="1.0.3" />
Hey, hello there π Welcome. I hope you will like this library β€οΈ
ConsoleCaptor is a library which will enable you to easily capture the output of the console for unit testing purposes.
Do you want to capture logs? Please have a look at LogCaptor.
- No mocking required
- No custom JUnit extension required
- Plug & play
- Zero transitive dependencies
- Java 8
- Java 11+
See the unit test ConsoleCaptorShould for all the scenario's.
public class FooService {
public void sayHello() {
System.out.println("Keyboard not responding. Press any key to continue...");
System.err.println("Congratulations, you are pregnant!");
}
}
import static org.assertj.core.api.Assertions.assertThat;
import nl.altindag.console.ConsoleCaptor;
import org.junit.jupiter.api.Test;
public class FooServiceShould {
@Test
public void captureStandardAndErrorOutput() {
ConsoleCaptor consoleCaptor = new ConsoleCaptor();
FooService fooService = new FooService();
fooService.sayHello();
assertThat(consoleCaptor.getStandardOutput()).contains("Keyboard not responding. Press any key to continue...");
assertThat(consoleCaptor.getErrorOutput()).contains("Congratulations, you are pregnant!");
consoleCaptor.close();
}
}
Initialize ConsoleCaptor once and reuse it during multiple tests with clearOutput() method within the afterEach method:
import nl.altindag.console.ConsoleCaptor;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
public class FooServiceShould {
private static ConsoleCaptor consoleCaptor;
@BeforeAll
public static void setupConsoleCaptor() {
consoleCaptor = new ConsoleCaptor();
}
@AfterEach
public void clearOutput() {
consoleCaptor.clearOutput();
}
@AfterAll
public static void tearDown() {
consoleCaptor.close();
}
@Test
public void captureStandardOutput() {
FooService service = new FooService();
service.sayHello();
assertThat(consoleCaptor.getStandardOutput()).contains("Keyboard not responding. Press any key to continue...");
}
@Test
public void captureErrorOutput() {
FooService service = new FooService();
service.sayHello();
assertThat(consoleCaptor.getErrorOutput()).contains("Congratulations, you are pregnant!");
}
}
There are plenty of ways to contribute to this project:
- Give it a star
- Make a donation through GitHub or open collective
- Join the Gitter room and leave a feedback or help with answering users questions
- Submit a PR