Introduction to Mockito and Unit Testing

Mockito is a Java unit testing framework for testing Java applications. It works by principle of mocking.

Wait, mocking? Yes, it works by mocking the real functionality of your application and helps you verify if your program performs as per your expectations when developing it and if not, you can easily pick up the errors in functionality by running test cases or even improve the design of your application by refactoring code as badly written code is difficult/impossible to write unit tests on.

Unit testing

Unit testing is a software development best practice whereby each testable functionality of an application is tested individually for correctness so as to avoid shipping bugs to production. This process can be automated and can run every time a build is triggered from your IDE or command line or even in a DevOps pipeline in your organization. Also, along the way after a program is running on production, new functionality can be required on top of the existing functionality. With unit tests, we have guards on our system and should any side effects be introduced by the new functionality, our unit tests will ‘scream’ and catch such errors. As such regression on updates becomes more efficient.

There are tons of aspects of using mockito and we are going to discuss each aspect individually with a sample real project. For this series, we shall use the school project under our Spring Boot CRUD example and write unit tests for the project.

Some of the scenarios we shall look at include but not limited to testing database CRUD operations without actually connecting to a database and test INSERTS, DELETES, UPDATES, QUERIES etc. and see how our application handles database operation errors. We can also test Http Calls to third party APIs and webservices,core banking web services etc. without opening an http call and test how our program handles http connection errors,retries,handling http response codes

We shall also add more functionality to the project so as to increase scope of learning to use the mockito framework.

Some of the topics we shall discuss include but not limited to;

  1. Setting up mockito into your project
  2. Mockito when/then
  3. Mockito spy
  4. Mockito times
  5. Mockito verify

Lets get started

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.