Appendix B. testing: Hold Your Code to Account

image

Everybody knows that good code needs to work.

But each code change that you make runs the risk of introducing fresh bugs that stop your code from working as it should. That’s why thorough testing is so important: it means you get to know about any problems in your code before it’s deployed to the live environment. In this appendix, we’ll discuss JUnit and KotlinTest, two libraries which you can use to unit test your code so that you always have a safety net.

Kotlin can use existing testing libraries

As you already know, Kotlin code can be compiled down to Java, JavaScript or native code, so you can use existing libraries on its target platform. When it comes to testing, this means that you can test Kotlin code using the most popular testing libraries in Java and JavaScript.

Let’s see how to use JUnit to unit test your Kotlin code.

Add the JUnit library

The JUnit library (https://junit.org) is the most frequently used Java testing library.

To use JUnit in your Kotlin project, you first need to add the JUnit libraries to your project. You can add libraries to your project by going to the File menu and choosing Project Structure → Libraries, or, if you have a Gradle project, you can add these lines to your build.gradle file:

image

Get Head First Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.