Better Unit testing with Mockito

Unit tests are like guidelines that help you test right. These guide your design to be loosely coupled, well etched out and provide fast automated regression for refactors and small changes to the code.

Best unit test case scenario is with an independent isolated class. Unit Testing is harder with dependencies on remote method calls, file system operations, DB operations etc.Unit testing means automation and minimum setup. All these dependencies require initial setup and take a very long time to execute. Also, it makes it almost impossible to test the class for the negative cases, eg: Network failure, File system not accessible, DB errors. You need to change the response of these dependencies to execute each unit test case for the class.

Mock comes to rescue unit tests. Mock doesn’t mean to make mockery of any object.

Mockito Framework

Mockito is an open source testing framework for Java. The framework allows the creation of Test Double objects called, “Mock Objects” in automated unit tests for the purpose of Test-driven Development or Behavior Driven Development. Mockito Framework enables mocks creation, stubbing and verification..

What is Object Mocking?
Mock objects simulate (fake) real objects and they use the same Interface(s) or class as the real object. A mock object allows you to set positive or negative expectations. The mock object lets you verify that the expectations were met or not, i.e. it records all the interactions which can be verified later.

When to Mock?
Object mocking should be conducted when the real object:

  • Has a behavior that is hard to cause or is non-deterministic.
  • Is slow and difficult to set up.
  • Has (or is ) a UI.
  • Does not exist For example,  Team A is working on X and requires Y from Team B, at the same time team B is working on Y, to start the task of X team A can mock Y.
  • Can simulate both behavior and ill-behavior.

To know more about Mockito,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s