Android Testing With JUnit5 and Kotlin - Part I

What is unit testing?

Unit testing is an essential part of development as it makes your code robust and allows you to catch bugs in your code in the early phase of the development. When developing android applications, there are two tests that you can write: local unit tests and Android instrumented tests. Local unit tests do not require an Android emulator or device as the tests run with the help of Java Virtual Machine. JUnit testing framework is usually used to test the application’s internal logic that does not require access to Android frameworks. Instrumented testing is used to test the UI of applications using an Android emulator or device. Android Studio supports different testing frameworks, including the one that I’ll be using, JUnit. JUnit is a testing framework that is automatically added to your project that you create with Android Studio. The JUnit version that comes with your project is JUnit4. However, I’ll show you how you can add JUnit 5 as your testing framework to conduct tests as it helps you better document your test cases compared to the previous version.

Add JUnit 5 dependencies

The first thing that we have to do to test our classes with JUnit5 is to include the following two lines in the app’s level gradle dependencies

Initialization

To test the Donut class, we’d first need to create a test file. In the project’s directory, we have three folders with the same package name; each package has a different use. We’ll create a DonutTest class under the package that has (test) following the package name. This is where we make all the test classes for unit tests. We’ll name our test class DonutTest, and initialize an instance of the Donut. Junit provides its lifecycle annotations to help us create well-managed tests.

Initializations in the JUnit framework usually take place in functions annotated with @BeforeAll or @BeforeEach. Test functions marked with @BeforeAll run first when we run out test class and are only called once, whereas methods with @BeforeEach annotations are called before each test. Since we need to create a Donut object only once, I’ll go ahead and put that in the function annotated with @BeforeAll. We could also initialize objects in a @BeforeEach function if there’s a logic that needs to be tested for a new instance of the class. In case you choose to add your initializations in @BeforeAll function, you’d need to change the declaration of the function to be static. Since Kotlin doesn’t have a static function as we use in Java, we’d need to annotate our test class with @TestInstance(TestInstance.Lifecycle.PER_CLASS).

This is the implementation of the Donut class