Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

How can we mock void methods in Mockito?

Answer»

Consider we have a method called updateItem() which internally calls a void method called updateItem() which interacts with the database and updates the object.

public Item updateItem(Item item) { if (item == null || item.getItemId() < 0) { throw new IllegalArgumentException("Invalid Id"); } itemRepository.updateItem(item); //void method that updates database state return item;}

We can mock the void method in the following ways:

1. doNothing-when: This is used when we do not want to check for the return parameters and skip the actual execution. When this mocked method is called, then it does nothing. The test case would be:

@Testpublic void updateItemTest() { Item item = new Item(2, "Item 1"); doNothing().when(itemRepository).updateItem(any(Item.class)); itemService.updateItem(item);}

2. doAnswer-when: We can also make use of doAnswer-when whenever we need to perform additional actions like computing return values based on method parameters when a mocked method is called. This is done using the following:

@Testpublic void updateItemTest() { Item item = new Item(2, "Item 2"); doAnswer((args) -> { System.out.println("doAnswer block entered."); assertEquals(customer, args.getArgument(0)); return null; }).when(itemRepository).updateItem(any(Item.class)); itemService.updateItem(item);}

3. doThrow-when: If we want to throw an exception from void methods or any normal methods, then we can use doThrow-when as shown below:

@Test(expected = Exception.class)public void updateItemTest() { Item item = new Item(3, "Item 3"); doThrow(new Exception("Item Invalid")).when(itemRepository).updateItem(any(Item.class)); itemService.updateItem(item);}Conclusion

Writing Unit Test Cases has various ADVANTAGES like design testability, code testability, enhances code maintainability and helps developers enforce object-oriented principles that aids to avoid code smells like LONG methods, large conditions, long classes etc. It helps to identify any existing logic flaw in the application. Due to these reasons, it has become important for developers to know how to unit test the functionalities developed by them. JUNIT is one such popular framework that has robust support for unit TESTING.

2.

Why can’t we mock static methods in Mockito?

Answer»

Static methods belong to the CLASS and not to any objects which means that all instances of the class use the same static method. They are more like procedural code and are used in legacy systems. Mock libraries create mocks at runtime utilizing dynamic instance creation using interfaces or inheritance. Since static methods are not linked with any instance, it is not possible to mock them using MOCKITO. However, we have FRAMEWORKS like PowerMock that SUPPORTS static methods.

3.

What is the main difference between @Mock and @InjectMocks?

Answer»

@Mock annotation is USED for CREATING MOCKS whereas @InjectMocks is used for creating class OBJECTS. Whenever the actual method body has to be executed of a given class, then we can use @InjectMocks.

4.

What is the difference between thenReturn and doReturn?

Answer»

THENRETURN and doReturn are used for setting up stubs and are provided by the Mockito framework. They are generally used along with when clause as --> when-thenReturn and doReturn-when. when-thenReturn is used in most cases due to better readability. 

Following are the differences between thenReturn and doReturn:

  • Type safety:
    doReturn takes OBJECT parameter, unlike thenReturn. Hence there is no type CHECK in doReturn at compile time. In the case of thenReturn, whenever the type mismatches during RUNTIME, the WrongTypeOfReturnValue exception is raised. This is why when-thenReturn is a better option whenever we know the type.
  • No side-effect:
    SINCE doReturn does not have type safety, there are no side effects when it is being used. Whenever thenReturn is used, if the type mismatch occurs, an exception is thrown which might result in the abortion of test cases.
5.

When and why should we use spy?

Answer»

Spy is a partial mock OBJECT supported by the Mockito framework. FOLLOWING are the features of spy objects:

  • Whenever mock is not set up, interaction on spy results in REAL METHOD calls. Spy objects allow verifying interactions such as whether the method was called and how many times it was called, etc.
  • They provide flexibility for setting up partial mocks. For instance, if an object has 2 methods, and we want one method to be mocked and the other to be called actually, then we can use spies.

The main DIFFERENCE between mock and spy is that in mock, we create a complete fake object whereas, in spy, we have a hybrid of a real object and fake/stubbed methods.

6.

What is Mockito? What are some of its advantages?

Answer»

Mockito is an open-source, Java-based, mocking framework that allows the CREATION of test objects that SIMULATE the behaviour (mock) of real-world objects. This helps in achieving test-driven or behaviour-driven development. The framework allows developers to verify system behaviours without ESTABLISHING expectations. Mockito framework attempts to eliminate expect-run-verify development patterns by removing external specifications and dependencies. Some of the advantages of Mockito are:

  • Mocks are created at RUNTIME, hence reordering method input parameters or renaming interface methods will not break test code.
  • Mockito SUPPORTS returning of values.
  • It supports exception simulation
  • It provides a check on the order of method calls.
  • It helps in creating mock objects using annotation.
7.

Why do we need mocking in unit testing?

Answer»

MOCKING is the process of creating and using mock objects that simulates the behaviour of real objects and is used to isolate the behaviour of the module under test from its external dependencies or services. These are particularly useful in unit testing and help in making unit test cases repeatable and PREDICTABLE. Mocking is required in the following cases:

  • Whenever the module under test has dependencies that are not fully implemented. For example, if we have a module that calls a REST API that is still in progress, then to test our module, it is advised to mock the API call and perform unit testing of our module.
  • Whenever the module under test updates the SYSTEM states. For example, whenever the module involves database calls that creates or updates or delete data from the system, it is very much IMPORTANT to mock those objects.
  • Even if we have DB calls that just retrieves the data, it is advised to mock those because of the risk of DB availability.