Android Unit Testing With Kotlin Part 1 Junit

Antwan Al Haddad
Jul 24, 2017 · 3 min read

Hello guys, in this post we gonna talk about Android unit testing and using kotlin instead of java.

What’s Unit Testing

Unit Testing is a level of software testing where individual units/ components of a software are tested. The purpose is to validate that each unit of the software performs as designed.

What to test with unit testing

Android unit testing is responsible to test your businesses logic, which means that you have to test only small methods or units of code to validate that its logic working as designed e.g. validating that specific input should gives you specific result

What we need to start

for this article we only need Junit 4 which will be added automatically with any new android project

testCompile 'junit:junit:4.12'

Naming convention for unit test methods

The good thing about unit test that it can be used as a documentation for your code so developers have to try always to keep their test method names are easy to understand and try to describe what they are testing here

and for this purpose i like to use this convention

MethodName_TheCaseThatYouTesting_TheExpectedResult

Junit Annotations

Before we start giving some real examples lets take a look on the most used Junit method annotations, what they do where we have to use them

In this figure we can see the order of the execution for each annotation

Lets take a look about what each method do :

@Test Annotation has two optional parameter

expected: that means you test method expecting an exception and if not this test will fail

timeout: specify time out for test method invocation and if the method invocation took more than what we expecting this test will fail beside the test result

Lets get our hands dirty

So Lets try to apply what’ve learned here and for that we will create class Book and add few methods is it to test

and then here is the test class which contain a test method about every things we talked about

Run your Test and check Test Coverage

you can either run you test normally

or you can run it with coverage

After your test run if you want to check your code coverage

then choose a folder where you wanna save the html report then you can open it in browser


Thanks for reading and for more On unit testing will be in the upcoming posts.

Antwan Al Haddad

Written by

Android Software Engineer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade