Android Testing With JUnit5 and Kotlin - Part II

Now that we’re finished with initializing our test class, we’re going to go through different ways to create actual tests. To create a simple test, we first need to annotate our test function with ‘@Test’. The test function does nothing but adds a null to a donut order. However, the test function passes because we aren’t testing anything. A well-created test function tests only one thing. Doing so not only makes test functions manageable, but it also makes the whole test class more readable.

Assertions are what allows us to test the functions. JUnit comes packed with several assertions, which enables us to perform different assertions depending on what values and types we want to test.
Few of the assertions that we are likely to use the most are:-
assertEquals – Helps us to check equality between expected and actual values. An expected value is the value that we expect a function to return and is the first argument to the assertion call, whereas an actual value is what the function returns and goes in as the second argument to assertion calls.
assertNotEqual – It is just the opposite of assertEquals. It helps us to assure that expected and actual values aren’t equal
assertTrue – Helps us to check if a condition is true
assertFalse – Checks if a condition is not true
assertNull – Allows us to assert that a value is null
assertNull – Checks if a value isn’t null
We won’t go through every assertion in this post, but the way we call assertions will be the same as those presented as examples in the post.

We’ll be using a few of the assertions to test our Donut functions. The first test function checks the total count of donuts in the order. For this, we will use ‘assertEquals’ because we know the value of the total number of donuts that we’ve added to our order, which is 5, and we will test it against the function in the Donut class.

Similarly, we test if the function would return 0 if there aren’t any donuts in the order.

Since the above tests are related to each other in that both the test functions test for the total count of donuts, we will group those tests. Nested tests allow us to divide our test functions into groups depending on how closely they are related.
To group the two functions, we’ll create a nested class, DonutCountTest. Nested classes should be annotated with @Nested. We’ll also include @DisplayName annotation, which allows us to provide a display name to our class so that when we run our test, instead of printing out the class name, it will print out what we put as an argument to the annotation. This allows us to improve the readability and documentation of what the test does.

For boolean checks, we can utilize assertTrue and assertFalse calls.

You can also checkout the full code of DonutTest at Github.