Javatpoint Logo
Javatpoint Logo

Methods of Mockito

The Mockito framework provides a variety of methods such as mock(), verify(), when(), etc., used to test Java applications. Using these predefined methods makes testing very easy.

The brief description of the Mockito methods are given below:

Mockito mock() method

It is used to create mock objects of a given class or interface. Mockito contains five mock() methods with different arguments. When we didn't assign anything to mocks, they will return default values. All five methods perform the same function of mocking the objects.

Following are the mock() methods with different parameters:

  • mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter.
    Syntax: <T> mock(Class<T> classToMock)
  • mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure. It is an advanced mock method, which can be used when working with legacy systems. It takes Answer as a parameter along with the class or interface name. The Answer is an enumeration of pre-configured mock answers.
    Syntax: <T> mock(Class<T> classToMock, Answer defaultAnswer)
  • mock() method with MockSettings: It is used to create mock objects with some non-standard settings. It takes MockSettings as an additional setting parameter along with the class or interface name. MockSettings allows the creation of mock objects with additional settings.
    Syntax: <T> mock(Class<T> classToMock, MockSettings mockSettings)
  • mock() method with ReturnValues: It allows the creation of mock objects of a given class or interface. Now, it is deprecated, as ReturnValues are replaced with Answer.
    Syntax: <T> mock(Class<T> classToMock, ReturnValues returnValues)
  • mock() method with String: It is used to create mock objects by specifying the mock names. In debugging, naming mock objects can be helpful whereas, it is a bad choice using with large and complex code.
    Syntax: <T> mock(Class<T> classToMock, String name)

Following code snippet shows how to use mock() method:

Mockito when() method

It enables stubbing methods. It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute.

Syntax: <T> when(T methodCall)

Following code snippet shows how to use when() method:

In the above code, thenReturn() is mostly used with the when() method.

Mockito verify() method

The verify() method is used to check whether some specified methods are called or not. In simple terms, it validates the certain behavior that happened once in a test. It is used at the bottom of the testing code to assure that the defined methods are called.

Mockito framework keeps track of all the method calls with their parameters for mocking objects. After mocking, we can verify that the defined conditions are met or not by using the verify() method. This type of testing is sometimes known as behavioral testing. It checks that a method is called with the right parameters instead of checking the result of a method call.

The verify() method is also used to test the number of invocations. So we can test the exact number of invocations by using the times method, at least once method, and at most method for a mocked method.

There are two types of verify() methods available in the Mockito class, which are given below:

  • verify() method: It verifies certain behavior happened once.
    Syntax: <T> verify(T mock)
  • verify() method with VerificationMode: It verifies some behavior happened at least once, exact number of times, or never.
    Syntax: <T> verify(T mock, VerificationMode mode)

Mockito spy() method

Mockito provides a method to partially mock an object, which is known as the spy method. When using the spy method, there exists a real object, and spies or stubs are created of that real object. If we don't stub a method using spy, it will call the real method behavior. The main function of the spy() method is that it overrides the specific methods of the real object. One of the functions of the spy() method is it verifies the invocation of a certain method.

There are two types of spy() methods available in the Mockito class:

  • spy() method: It creates a spy of the real object. The spy method calls the real methods unless they are stubbed. We should use the real spies carefully and occasionally, for example, when dealing with the legacy code.
    Syntax: <T> spy(T object)
  • spy() method with Class: It creates a spy object based on class instead of an object. The spy(T object) method is particularly useful for spying abstract classes because they cannot be instantiated.
    Syntax: <T> spy(Class<T> classToSpy)

Following code snippet shows how to use the spy() method:

Mockito reset() method

The Mockito reset() method is used to reset the mocks. It is mainly used for working with the container injected mocks. Usually, the reset() method results in a lengthy code and poor tests. It's better to create new mocks rather than using reset() method. That is why the reset() method is rarely used in testing.

The signature of the reset() method is:

Mockito verifyNoMoreInteractions() method

It is used to check that any of the given mocks have any unverified interactions. We can use this method after verifying all the mock, to make sure that nothing else was invoked on the mocks. It also detects the unverified invocations that occur before the test method, for example, in setup(), @Before method, or the constructor. It is an optional method, and we don't need to use it in every test.

The signature of the verifyNoMoreInteractions() method is:

Mockito verifyZeroInteractions() method

It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.

The signature of the verifyZeroInteractions() method is:

Mockito doThrow() method

It is used when to stub a void method to throw an exception. It creates a new exception instance for each method invocation. There are two types of doThrow() methods available in the Mockito class with different parameters, as shown below:

  • doThrow() method with Throwable: This method is used when we want to stub a void method with an exception. Syntax: doThrow(Throwable toBeThrown)
    The signature of the doThrow() method is:
  • doThrow() method with Class: This method is used when we want to stub a void method to throw an exception of a specified class.
    Syntax: doThrow(Class<? extends Throwable> toBeThrown)
    The signature of doThrow() method is:

Mockito doCallRealMethod() method

It is used when we want to call the real implementation of a method. In other words, it is used to create partial mocks of an object. It is used in rare situations, such as to call the real methods. It is similar to the spy() method, and the only difference is that it results in complex code.

The signature of the doCallRealMethod() method is:

Mockito doAnswer() method

It is used when we want to stub a void method with a generic Answer type. The signature of the doAnswer() method is:

Mockito doNothing() method

It is used for setting void methods to do nothing. The doNothing() method is used in rare situations. By default, the void methods on mock instances do nothing, i.e., no task is performed.

The signature of doNothing() method is:

Mockito doReturn() method

It is used on those rare occasions when we cannot use Mockito.when(object). The Mockito.when(object) method is always suggested for stubbing because it is argument type-safe and more readable as compare to the doReturn() method.

The signature of doReturn() method is:

Mockito inOrder() method

It is used to create objects that allow the verification of mocks in a specific order. Verification done in order is more flexible as we don't have to verify all interactions. We need to verify only those interactions that are interested in testing (in order). We can also use the inOrder() method to create an inOrder object passing mocks that are relevant for in-order verification.

The signature of Mockito.inOrder() method is:

Mockito ignoreStubs() method

It is used to ignore the stubbed methods of given mocks for verification. It is useful with verifyNoMoreInteractions() or verification inOrder() methods. It also helps in avoiding redundant verification of stubbed calls.

The signature of the ignoreStubs() method is:

Mockito times() method

It is used to verify the exact number of method invocations, which means it declares how many times a method is invoked. The signature of the times() method is:

Mockito never() method

It is used to verify that the interaction did not happen. The signature of the never() method is:

Mockito atLeastOnce() method

It is used to verify the invocation at-least-once that means the method should be invoked at least once.

The signature of the atLeastOnce() method is:

Mockito atLeast() method

It is used to verify the invocation at least x number of times. For eg., given atLeast(3) means the method will invoke a minimum of three times.

The signature of the atLeast() method is:

Mockito atMost() method

It is used to verify the invocation at most x number of times. For eg., given atMost(3) means the method will invoke a maximum of three times.

The signature of the atMost() method is:

Mockito calls() method

It allows a non-greedy verification in order. It can only be used with the inOrder() verification method. For eg., inOrder.verify(mock, calls(3)).xyzMethod("...");

The signature of the calls() method is:

Mockito only() method

It checks that the given method was the only invoked method. The signature of the only() method is:

Mockito timeout() method

It allows Mockito to perform verification with a timeout. It instructs a verify to wait for a specific period of time for a particular interaction rather than to fail immediately. It may be useful for testing in existing situations.

The timeout() method differs from the after() method as after() method waits for the full period unless the final result is declared whereas the timeout() method will stop as soon as the verification passes. It is rarely used in testing.

The signature of the timeout() method is:

Mockito after() method

It allows Mockito to verify over a given period of time. We have already discussed that the after() method differs from the timeout() method.

The signature of the after() method is:

Mockito validateMockitoUsage() method

It is used for explicitly validating the framework state to detect the invalid use of the Mockito framework. It is an optional feature of Mockito because it validates the usage all the time. Both, the built-in runner (MockitoJUnitRunner) and the rule (MockitoRule) calls the validateMockitoUsage() method after each test method.

The signature of the validateMockitoUsage() method is:

Mockito withSettings() method

It is used to create mocks with additional mock settings. It should be used occasionally in testing. Instead of using the withSettings() method, create simple tests using simple mocks. The main reasons for using the MockSettings are

  • By using MockSetting, we can easily add other mock settings when needed.
  • It combines different mock settings without messing up the code.

The signature of the withSettings() method is:







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA