To verify that a specific method was not called Using Mockito, we have multiple methods. In this blog, we will learn how to verify that a specific method was not called using Mockito in detail.
Table of Contents:
Method 1: Using verify() function
We can verify that a specific method was not called using Mockito by using verify() with times(0) verification mode. Let’s learn this with an example:
Syntax:
verify(mockObject, times(0)).methodName(arguments);
Where:
- mockObject is the object created using Mockito class,
- methodName is the name of the specific method
Code:
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
class Example {
void methodToCall() {
System.out.println("methodToCall was called");
}
void methodNotToCall() {
System.out.println("methodNotToCall was called");
}
}
public class MockitoTest {
public static void main(String[] args) {
Example mockExample = mock(Example.class);
mockExample.methodToCall();
verify(mockExample, times(1)).methodToCall();
verify(mockExample, times(0)).methodNotToCall();
}
}
Explanation: Here, we have used times() function to check whether a function is called or not. times(0) means the function is not called, times(1) means it is called exactly once.
Method 2: Using never() function
We can use the never() function to verify that a specific method was not called using Mockito. This is the simplest method and is used for better readability of the code.
Syntax:
verify(mockObject, never()).methodNotToCall();
Code:
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
class Example {
void methodToCall() {
System.out.println("methodToCall was called");
}
void methodNotToCall() {
System.out.println("methodNotToCall was called");
}
}
public class MockitoTest {
public static void main(String[] args) {
Example mockExample = mock(Example.class);
mockExample.methodToCall();
verify(mockExample, times(1)).methodToCall();
verify(mockExample, never()).methodNotToCall();
}
}
Explanation: Here never() function checks that a specific method was never called.
Conclusion
So far in this article, we have learned two different methods to verify that a specific method was not called using Mockito. Mockito is an open-source framework with an active community of developers. This means that users have access to continuous improvements, bug fixes, and support from the community. If you want to learn more about Java, you may refer to our Java course.
FAQs
What is Mockito?
Mockito is a Java testing framework used to create mock objects for unit testing
Is Mockito part of Spring boot?
Mockito is not a part of Spring Boot, but it is commonly used alongside Spring Boot for unit testing.
How to clear mock after each test?
You can clear mocks after each test by using Mockito.reset(mockObject) inside a @After method.