Are you looking for a way to test your console output (println()) in your Kotlin project?
In this post, I’m going to walk you through the process of creating a simple project setup that allows you to unit test the console output of the application.
The project will use Gradle but you can achieve the same effect using Maven, just adjust the dependencies to your needs.
Setting up the Gradle project
Create a new folder and begin the project initialization process there.
Then, answer the questions accordingly.
The project has been generated, it’s time to open it in the IDE.
By default, the application will have a default test environment already set up, with basic asserters and the JUnit library in place.
It happens thanks to these out-of-the-box dependencies:
In order to be able to test console output, we will use a helpful library called system-lambda. It allows us to get the System class output streams as the convenient lambda functions.
Don’t worry about the compatibility between this library which uses java.lang.System class and Kotlin.
Why? Take a quick look at the Kotlin internals. The
println() method is just a wrapper for the good old Java
Add the dependency into the build.gradle.kts file:
Testing the console output
Let’s put this in action. At first, let’s modify the existing test class and let the generated application greet us 👋
Then run it. No surprises, it’s all green.
For the sake of clarity, let’s change the implementation and test case little bit (because this project is the pocket-adder after all).
And the test class:
The test is passing 🟢 .
As you can see, getting your console output in the unit tests is very simple and straightforward.
This setup will be used for the series of posts about design patterns in Kotlin, if you’re interested read more here.