Intive Blog

Unit testing with Mockito

One of the challenges that come up by making unitary tests is that we find that the component being tested is dependent on others, which would lead us to have to instantiate and configure them, all these involve too much time and labor. To avoid this then we can substitute Mocks for components.


What are Mocks? They are objects that mimic the behavior of real objects, through the implementation of a single interface, providing results determined independently from complex processes or interactions that the real object may have. These are used to simulate the behavior of complex objects whenever this is impossible or impractical when using the actual object along the test. For example, when the object in question yields nondeterministic results (time, temperature), it is difficult to create its state or play it, it may be slow (access to a DB), or its behavior may change. Thus the problem arising from interdependent objects is solved, those in which in order to test the first, a non-tested object has to be used, which makes the test not valid.


Mockito is a Java API widely used for testing, based on EasyMock, created to simplify the use of EasyMock with a more natural and practical API.

 

Example of usage:

  1. A class instance is created to test passing the class type to the mock constructor
2. The method behavior desired under test is set by using
where in when( ) the call to the method to be tested is placed and in thenReturn( ) what you want it to give back.
So, for example, if that call to the method is printed, it will give back the string which was passed on to the thenReturn(),, and if no value had been set, it will give “null” back.
Through then( ), you can verify whether a specific method was applied, and the amount of times applied by using should( ):
 

Mode of usage

  • To the class to be mocked, the entry @Mock is added
  • The mock class on the @Before is initialized.
Thus, through Mocks we simplify processes and gain lots of precious time.

For further information, you can visit:

Jasmina Sella Faena

She was a software developer at intive – FDV where she took part in the Java Team. Among her skills she highlights working with technologies such as Git, Java, Python or Smalltalk. She is a student of computer engineering at the Universidad de Buenos Aires. Her hobbies are doing sports and playing instruments.

Add comment