There are cases when you want to write test cases for your method, but the method itself usage some other method or service, in these scenarios we try to skip the inner methods call or service by mocking it up.
Mockito is very famous mocking api. With this you can mock any object and just focus on testing of your method only.
Let’s quickly jump into Spring boot JUnit configuration. Add following lines in pom.xml
Once you add boot starter, it will automatically add following dependencies to your project.
- Basic JUnit.
- Spring unit test framework
- Asserts - AssertJ, Hamcrest Assert, JSONAssert, Java assert
Common Mockito function and usage.
Using Mockito annotation In order to make mockito annotations work you would to use one of the below methods.
- Init Mockito first – MockitoAnnotations.initMocks(this)
- Or use Mockito runner – @RunWith(MockitoJUnitRunner.class)
Earlier we have sued when with then return, ‘when+thenReturn’ has some limitation such it can’t work void method also, if you don’t use mocked object in ‘when’ it might call function on actual object and throw some errors. While doreturn+when handles both the scenarios well. It doesn’t call actually method of object but it mocks the function call.
Same as doRetrun, doThrow can throw a exception on specific method of the object. doThrow(NullPointerException.class).when(emp).getEmployee(anyInt());
Add a Spy
Mockito provide a utility a object which keeps an eye on the target object. It tracks the interactions on target object.
Call real object
In a class you can mock all the methods, but in case you want to call a real method on the class. when(emp.getId()).thenCallRealMethod(); // will call real method rather than mocked one.
Inject mock takes a mock object and inserts into another object just like autowiring.
Mock vs Spy.
Spy is a wrapper around actual instance and tracks the activity on instance while mock is bare-bone mocked instance created for the class. Use spy when you want to track activity on object it works on actually object, use mock when you just want bare-bone object of the class. EmployeeDao employeeDao = mock(EmployeeDao.class); // create a mocked object of the class EmployeeDao employeeDao = spy(new EmployeeDao())); //creates new actual object and wraps a spy
You might have seen anyInt(), anyString() passed in argument of method when using ‘when’ or doReturn feature of mockito. These are ArgumentMatcher, you don’t need to pass actual values but can match with a argument type or so. For custom class you can use any(CustomClass.class). There is option to create customer matcher as well.