HomeJavaHow to use Built-In Verification Modes of Mockito Mocking Framework

How to use Built-In Verification Modes of Mockito Mocking Framework

Mockito Mocking Framework Overview

Mockito is an open source testing framework for Java which is released under the MIT License.

The official documentation of this framework states

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesnā€™t give you hangover because the tests are very readable and they produce clean verification errors.

#Using the built in Verification Modes

Mockito provides a number of convenient static methods for creating VerificationModes.Ā These methods are available in the package org.mockito.Mockito.

#times(int)

This method will verify that the method has been call n-number of times.

@Test
public void mockito_verification_times_1() {
	// Given
		
	// When
	mockMethod.mockMethodTestPage();
		
	// Then
	verify(mockMethod, times(1)).mockMethodTestPage();		
}

Note thatĀ verify(mock)Ā is an alias ofĀ verify(mock, times(1)).

#atLeastOnce(), atLeast(int)

This method will verify that the test was called at least the given number of times.

@Test
public void mockito_verification_atleastonce() {
	// Given
		
	// When
	mockMethod.mockMethodTestPage();
	mockMethod.mockMethodTestPage();
		
	// Then
	verify(mockMethod, atLeastOnce()).mockMethodTestPage();		
}
@Test
public void mockito_verification_atleast_2() {
	// Given
		
	// When
	mockMethod.mockMethodTestPage();
	mockMethod.mockMethodTestPage();
	mockMethod.mockMethodTestPage();
		
	// Then
	verify(mockMethod, atLeast(2)).mockMethodTestPage();		
}

#atMost(int)

This is to verify that the method has been called at most the given number of times.

@Test
public void mockito_verification_atmost_3() {
	// Given
		
	// When
	mockMethod.mockMethodTestPage();
	mockMethod.mockMethodTestPage();
		
	// Then
	verify(mockMethod, atMost(3)).mockMethodTestPage();		
}

#never()

This is to verify that the method is never used.

@Test
public void mockito_verification_never() {
	// Given
		
	// When
		
	// Then
	verify(mockMethod, never()).mockMethodTestPage();		
}

#only()

This is to verify that the method being verified was the only method of the mock called.

@Test
public void mockito_verification_only() {
	// Given
		
	// When
	mockMethod.mockMethodTestPage();
		
	// Then
	verify(mockMethod, only()).mockMethodTestPage();		
}

Note: If we have more than ONE method called in the mockMethod interface then this test will fail and produce the error description.

RELATED ARTICLES

Most Popular