JUnit Testing in Android with Kotlin for Beginners | Hemcrest and Mockito

~ The More Code you write Without Testing, The more paths you have to check for Errors

Puneet Grover
Nerd For Tech

--

Being an Android developer when I started learning JUnit Test cases, I had to visit so many websites to learn it, Every content has their own unique style of representing Unit testing But I’ve not found a single place where I can go step by step and learn JUnit Test cases, But No Worries That’s the reason here I am with this topic

Here I’ll be covering only JUnit Testing only But Stay tuned for next topic which will be UI Testing with Expresso

Ok No More discussions, let’s go step by step:-

What is Unit Testing?

  • Try and test a specific unit (Specific boundary)
  • Unit can be a single method, or a group of methods or a set of group of classes

Advantage of Unit Testing

Once I write unit test I will be able to run unit test automatically within milliseconds and check whether all conditions for that particular method passing or not / Or we can say To Ensure a function does what it is supposed to do

Create First Junit Testcase

Let’s take an example of a class for which we want to write test cases, It has one method isPositiveNumber which returns true if number is positive else false

  • Right click on class name of which you want to write test case, Navigate to GoTo-> Test

Annotations

Let’s learn about Annotations first

Before:-

  • If we want to perform some operation before test gets executed like initializing some variables etc
  • It tells Junit that this method must be run before each single test case

@Test:-

  • Test in Junit are methods annotation with @Test annotation
  • Here I’ll write actual test — How?
  • I’ll need to call methods SUT & make sure that it produces expected outputs

Note:- SUT = System under test, Standard way of naming Class for which you’re writing test cases

  • Calling that class method (isPositiveNumber()) to test with @test annotation
  • I can assert / check that method with the conditions to see if expected output comes or not
  • In above example, negative number is passed as an argument
  • assertTrue() checks if output is true that means test is passed otherwise failed
  • Test will be fail as output will be false

Naming of Unit Test

This is how we should name our functions/unit test cases, although not compulsory but that’s the standard way of naming testcases

<unitOfWork>_<stateUnderTest>_<expectedBehaviour>

Hamcrest library

  • Hamcrest is the well-known framework used for unit testing
  • It’s bundled in JUnit and simply put, it uses existing predicates — called matcher classes — for making assertions

Example:-

  • Created a class StringReverser with a method reverseString()
  • Created a Test Case and used hamcrest library to assert the response
  • As you can see we used assertThat() function with argument contains `is` which is a part of following package:-
    “import org.hamcrest.CoreMatchers.*”
  • Hence this test tests that when empty string is fed into reverse method, empty string is returned because the reverse of empty string is also empty string
JUnit testing using hamcrest

I hope you got some idea how we write unit test cases in android 🤘

Let’s move to Mockito

Mockito in Android with Kotlin

  • Mockito is a framework in android which helps in initialisation of your classes you want to test i.e create your mocks
  • Basically in real scenario we may have complex classes which can contain many dependencies so It’s not always possible to manually intialize a class and here Mockito comes to rescue

Two ways we can mock a class/object

One is use @Mock annotation

Second is to use mock function

It creates mock object of a class/interface which takes classToMock as a parameter

Mockito Test Runner

  • Annotate test with JUnit special @RunWith. And then define MockitoJUnitRunner as its parameter
  • After this I don’t have to initialize objects/mocks explicitly — Just annotate them with @Mock
  • Mockito is a special framework that reduce the effort involved in implementation of Test Doubles

Unit test classes that have external dependencies known as Test Doubles

Hope you’re able to catch things, I’ve used very simple steps to make you understand — Only I need is some patience But believe me you won’t have to go anywhere on any other website to start your test cases after this

Let’s learn one another most important use of Mockito

verify in mockito

verify is Mockito’s assertion that verifies that some method was called on specific mock

  • Example — verify(operators).add(a, b)
  • That means verify on operators object that if add method is called or not

So sometimes we don’t need the response of a method, we just wanted to know if a function is called or not depends on our condition and here verify method comes into picture

  • Also we have some more functions of mockito like when, thenReturn kind of methods to test our units

Example — Mockito test case NetworkHelper Class

I’ve written a class named NetworkHelper which has one method isConnectedToNetwork which always return true

Let’s see NetworkHelperTest using Mockito:-

References:-

Watch my Youtube video on Unit Testing at CodingWithPuneet

Unit Testing by Puneet Grover at CodingWithPuneet

Don’t forget to Subscribe my Youtube Channel as well 😁

That’s it Guys! I wish and I hope that you all have got good idea of how to write unit test cases, I know It was bit lengthy but worth reading too

See you all to next session and Doooooon’t forget to follow me on:-

Medium, Linkedin and Twitter

Happy Coding!

--

--

Puneet Grover
Nerd For Tech

Android Team Lead (Senior Consultant) @Deloitte USI | Google Certified Android Dev | Java | Kotlin | Blogger | Sometimes Youtuber