Table of contents
1.
Introduction
2.
Mocking and its Need
3.
Mockito
4.
Best Practices
4.1.
Readability
4.2.
Breakdown Components
4.3.
Ignoring Trivial Tests
4.4.
Testing, then Debugging
4.5.
Using Correct Verifying Method
4.6.
Using Correct Matching Method
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Best Practices in Mockito

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Let’s say we have a REST or SOAP API that can be called by clients, receive requests and return responses dependent on the requests as well. But, until and unless it is tested in a real world scenario we won’t be able to grasp how our API manages the traffic when the site is hosted. This is the basic idea when we are mocking an API using a virtual service that mocks the real service.

Mockito is a java based library that can be used as a mocking framework to create simple and basic test APIs for performing unit testing of Java Applications. This can be used as unit testing as well when we are mocking a few classes and their behaviour that are external and included in a test suite.

Let’s learn about how using some of the best practices in mocking and mockito we are able to get the best out of these framework and library.

Mocking and its Need

Mocking is essential when we are cloning real objects and testing them in place of testing real objects to mock them into applications that are working under similar conditions to real world applications.

Mocking can be used for many real world applications when it comes to using unit testing in development.

The first case would be when we want to test components that are dependent on other components that are under development right now. Here, we can either wait for the other component to be completed to test the dependent component. Or we can mock the component that is currently in production. This is one of the most essential ways in which mocking can be used for testing.

Let’s say a particular component takes a long time to deal with some of the queries that may take over 20 seconds to complete the read/write operations associated with the component. In this case we simply require making a mock object to perform testing and where mocking can shine.

In a case where we want to create a connection to the database but are not able to do it because of configuration issues. Here we can mock components so as to test the component irrespective of the fact that configuration was still an issue.

Mockito

Mockito is a java based library that is used as a unit testing framework that uses mocking as a crucial component in developing testable applications. Mockito is an open-sourcing testing framework under the MIT Licence. It generates mock objects for a specific interface with particular specifications using the Java Reflection API. Java Reflection API is an API that is used to examine or modify the behaviour of methods, classes, interfaces at runtime. Mockito can be used together with JUnit and TestNG as well. Along with several other benefits like exception handling and order checking Mockito works as one of the best java mocking frameworks.

Best Practices

Writing a unit test generally includes:

  • Mocking the components that are under development right now and are external to the unit, but required by the unit to be tested.
  • Putting the components to use and asserting the data that is returned by it and verifying both the calls and the exceptions using Mockito.

However, in these steps there are some good practices that should be followed in order to make your unit test use it’s utmost capabilities.

Readability

When writing test suites and methods we seldom name them to mean what they are mocking or testing. When we change our naming convention such that we make out the function of the logical unit we make sure that the reader or any other developer understands exactly what our test does. This increases the readability of the test suites, thus increasing the accessibility of our code even without the need of proper documentation or the developer reading the whole piece of code.

Some examples of good test method names would be:

should_throw_exception_request_invalid
should_return_valid_user
You can also try this code with Online Java Compiler
Run Code

Breakdown Components

When testing a component, we must make sure all the corner cases are covered so that in the unexpected scenarios presented by the real world it does not break. This covers one of the extreme programming concepts in which we test all different combinations that could break and make sure that no class with a sliver of error is missed.

Ignoring Trivial Tests

Some of the test cases are trivial when it simply acts as a getter or setter and basically increases the number of calls and tests that can dramatically increase development and application build time. Thus, in an attempt to test redundant cases we decrease our maintainability and miss more useful test cases.

Testing, then Debugging

Usually when we see a bug we go to make it vanish from the existence of your application. However, before we go in to squish our bug we must first make assert the bug we are trying to squish. Because, there are numerous cases in which the apparent bug is solved but the actual bug persists and we are not able to recognise it until and unless it puts our application in danger of breakdown.

The best approach in cases like these would be to make more tests that break the code and thus are able to narrow down the bug to the lowest possible unit and thus enrich our test suites and increase our documentation with it. 

Using Correct Verifying Method

When we are verifying our calls we have to be very specific as to which method best asserts the behaviour expected from the piece of code.

For example we have to check two units. One where we assert whether the call is made at least once and another we have to make sure the call is made n times exactly. Here both the tests are very different and require very specific methods to test them as well. Thus, we have to first find the best suited method from many modes like atLeast(), atLeastOnce(), atMostOnce(), which are not the best ways because of how ambiguous they can be at times. times(), however is able to best assert our components by passing the desired number of calls.

Using Correct Matching Method

Asserting the type of data passed as parameters is one of the most important yet the most ignored part of any test case. Asserting parameters against their expected state is a better approach than just overlooking it.

Thus, in asserting parameters we prevent it from changing, not throwing any error in case the code is changed and we are not able to assert the current state. This increases our test accuracy dramatically.

FAQs

1. Can I mock private methods?

Ans: When private methods are asserted from a standpoint of testing, these methods do not exist as they are not accessible to the test suite.

 

2. What values do mocks return by default?

Ans: By default, mocks return values like zeros, falseys, nulls that are also known as ‘nice’ values. This makes sure the mocks are completely transparent and not obtrusive of the tests.

 

3. How do I mock an extension method?

Ans: If mockito is not able to access a method by overriding it it can not mock it and thus other alternative methods are used.

 

4. What is a mockito spy?

Ans: A Mockito spy is a partial mock that can mock a part of an object by mocking only a few methods while real methods are invoked for others.

 

Key Takeaways

In this blog, we discussed how we are able to best use mockito, the java based mocking library using the best practices.

You may want to learn more about why we need mocking here.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Learning!

Live masterclass