Tuesday, August 8, 2017

Unit Testing with Mockito

Mockito is a mocking framework, It lets you write tests with a clean & simple API. Following steps need to be performed to test your code using Mockito.

1) Include following dependency in your pom.xml

2) Annotate Test class with @RunWith(MockitoJUnitRunner.class)

3) Use annotation  @Mock or mock() for creating mocks.

4) Use annotation  @InjectMocks for  injecting mocks/spies fields annotated with @Spy or @Mock

5) Use annotation @Spy or spy() for partial mocking, real methods are invoked but still can be verified and stubbed

6) Use annotation @Before for method if something you want be applied for all your tests. For example if you want to mock dependency which is applicable for all test methods.

7) Use verify()  to check methods were called with given arguments
8) Finally @Test annotation for testing methods.

Here is the complete example of Test class using Mockito

a) Class which needs to be mocked and tested 



b) Test Class 


This example will give you fair Idea how to mock Class and Test it using mockito. In next blog, I shall be covering some of other aspects as well like mocking Future Interface or using Spy, Use of Before and Mocking Rest Controllers of Spring.