Top Mockito Interview Questions and Answers

1. What is Unit Testing?

Unit Testing is a method of testing the smallest piece of code called a unit. The main aim is to isolate each unit of the system to identify, analyze and fine-tune the defects. 

2. What are the Benefits of Unit Testing? 

  • Reduces bugs when transmuting the existing functionality. 
  • Reduces the Cost of Testing as defects are captured in the very early phase. 
  • Ameliorates design and sanctions better refactoring of code.


3. What is the Mockito framework? 

Mockito is a mocking framework. It is a Java-based library used to engender simple and basic test APIs for performing unit testing of Java applications. It can additionally be utilized with other frameworks such as JUnit and TestNG. 

4. What is mocking?

Mocking is primarily utilized in unit testing. An object under test may have dependencies on other objects. To isolate the behaviour of the object we optate to supersede the other objects by mocks that simulate the behaviour of the real objects. This is utilizable if the genuine objects are impractical to incorporate into the unit test.
In short, mocking is engendering objects that simulate the behaviour of real objects.

5. What are the steps to be performed while using the Junit with Mocking framework?

  • Initialize required objects for working with mocks and tested method
  • Set the mock behaviour on dependent objects
  • Execute the tested method
  • Perform assertions
  • Verify if a method is invoked or not

6. What is the use of the mock() method?

The Mock() method is used to create and inject the mocked instances. The other way of creating the instances is using the @mock annotations.

mock() method example,

public class MockitoMockMethodExample {

@SuppressWarnings("unchecked")
@Test
public void test() {
// using Mockito.mock() method
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(5);
assertTrue(mockList.size() == 5);
}

}

Mockito @Mock Annotation example,

public class MockitoMockAnnotationExample {

@Mock
List<String> mockList;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}
@SuppressWarnings("unchecked")
@Test
public void test() {
when(mockList.get(0)).thenReturn("Knowledgefactory");
assertEquals("Knowledgefactory", mockList.get(0));
}
}

7. Difference between Assert and Verify?

Assert: If the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test steps will not be executed. 

Verify: There won't be any halt in the test execution even though the verify condition is true or false.

8. How do you mock static methods?

That can be done using PowerMockito. PowerMockito is a PowerMock's extension API to fortify Mockito. It provides capabilities to work with the Java Reflection API in a simple way to surmount the quandaries of Mockito, such as the lack of ability to mock final, static or private methods.

To use PowerMock with Mockito, we need to apply the following two annotations in the test:

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.knowledgefactory.dev.demo.*")

9. What is ArgumentCaptor in Mockito?

Mockito ArgumentCaptor is utilized to capture arguments for mocked methods. ArgumentCaptor is utilized with Mockito verify() methods to get the arguments passed when any method is called. This way, we can provide supplemental JUnit assertions for our tests.

10. What is the difference between mocking and spying?

The difference is that in mock, we are engendering a complete mock or fake object while in spy, there is the real object and you just spying or stubbing concrete methods of it. While in spy objects, of course, since it is a genuine method when we are not stubbing the method, then it will call the real method behaviour. If we optate to transmute and mock the method, then we require to stub it.

11. List some Mockito Annotations?

  • @Mock - It is used to create and inject mocked instances.
  • @Spy - It is used to create a real object and spy on the real object.
  • @Captor - It is used to create an ArgumentCaptor.
  • @InjectMocks - It is used to create an object of a class and insert its dependencies.
  • @RunWith - It is utilized to keep the test clean and improves debugging. It additionally detects the unutilized stubs available in the test and initializes mocks annotated with @Mock annotation.

12. What is Hamcrest used for?

Hamcrest is a assert framework for testing libraries like JUnit. Hamcrest allows checking for conditions in our code via subsisting matcher classes. It additionally sanctions us to define our custom matcher implementations.

13. What is the use of @Spy annotation?

The @Spy annotation is used to create a real object and spy on that real object. A spy helps to call all the normal methods of the object while still tracking every interaction, just as we would with a mock.

For Example,

@Spy
HashMap<String, Integer> hashMap;
@Test
public void saveTest()
{
hashMap.put("Earth", 10);
Mockito.verify(hashMap, times(1)).put("Earth", 10);
Mockito.verify(hashMap, times(0)).get("Earth");
assertEquals(1, hashMap.size());
assertEquals(new Integer(10), (Integer) hashMap.get("Earth"));
}

14. What is the use of @Captor annotation?

We can use @Captor annotation to create an argument captor at the field level. So instead of initializing field level ArgumentCaptor as:

ArgumentCaptor acDouble = ArgumentCaptor.forClass(Double.class);

We can use @Captor annotation to create an argument captor at the field level. So instead of initializing field level ArgumentCaptor as:

We can use @Captor as:

@Captor ArgumentCaptor aDouble;

15. What is the difference between @InjectMocks and @mock?

@Mock creates a mock implementation for the classes you need.

@InjectMock creates an instance of the class and injects the mocks into it.

For example

@Mock
UserDao userDao;

@InjectMocks
UserService service;

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}

More Java interview questions and answers...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete