What does the when() method do in Mockito?

What does the when() method do in Mockito?

A) It sets up the behavior of a mock object
B) It verifies the method calls on a mock
C) It initializes a mock object
D) It cleans up mock objects after a test

Answer:

A) It sets up the behavior of a mock object

Explanation:

The when() method in Mockito is used to set up the behavior of a mock object. It specifies what the mock should do when a particular method is called. This method is typically followed by thenReturn() or thenThrow() to define the expected result or exception.

For example:


when(mockObject.someMethod()).thenReturn(someValue);

In this example, when someMethod() is called on mockObject, it will return someValue. This allows you to simulate the behavior of dependencies and test how the code under test responds to different scenarios.

Reference links:

https://www.javaguides.net/p/mockito-tutorial.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top