Thursday, March 10, 2016

Mockito for better unit tests

Today I'm going to introduce you a very nice framework that allows you write good unit tests that cover only the parts of code that you want to test and stub all other dependencies .. but obviously in order to do that your code must be written in a testable way.

To know more about testability please refer to this wiki document.

  • What is Mockito?
  • How to use it?
  • Example
What is Mockito?

Mockito is a framework that  allows you writing unit tests that only test your piece of code by mocking and stub all other components that your piece of code depends on.

In other words if you want to test your integration with other libs and components then its not unit test any more .. its called integration test which is not covered in this post.

How to use it?

You can configure mockito using maven or simply download the lib from here.

For maven configuration you can define the dependency in your pom.xml as here.


Note: I will use junit in the following example and in case you are not familiar with junit please refer to this.

Let's start by a very simple example that you have a class that reads a comma separated String and return it as a List<String> .. It reads this String by calling another class CSVReader that can either read it from file/database/network .. so in case you want to test your class only without being dependant on the CSVLineReaderClass you should mock the reader class.


Usually when running unit tests you need to get rid of the overhead of setting up other dependencies and want to see how your class/function behaves not how others behave.

Implementation of CSVLineParser:

The unit test should look like this, and you can add more test cases :).

When you run the test cases you will see the nice green results which means that all cases have passed correctly.

When you do something wrong like this :) .. you will see the unit tests failing.


In fact that's really nice, its really safe when you or someone else in your team mistakenly does these kind of stupid issues, its better to catch it during development than catching it in pre-production or on production and embrasse yourself and your team :D.

Mockito has way more than this simple example, but as usual I like to introduce you with very small nice things and then you can continue reading and see other features of the framework :).

I hope you like it.

1 comment: