Junit 5 Mockito Verify Example

In this example I am going to show you how to verify a method has been executed at least. Why do you need to verify method execution? Consider the void method, in your Java class, which you want to perform Junit test case on it and you don’t have any way to tell whether your method successfully tested or not. So here you are left with only one option, i.e., to check whether your method was executed or not. If your method was executed then you know that your code was executed for the intended functionality.

To actually verify your method in Junit test case you need to use Mockito’s verify() method. Read if you need Junit 4 version of Mockito’s verify() method.


Java at least 8, Gradle 6.5.1 or Maven 3.6.3, Junit 5.7.0

Project Setup

You can create gradle or maven based project in your favorite IDE or tool. The name of the project is java-junit-5-mockito-verify.

If you are using gradle as a build tool for your project then you can use below build.gradle script.

plugins {
    id 'java-library'

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
	testImplementation 'org.junit.platform:junit-platform-engine:1.7.0'
	testImplementation 'org.mockito:mockito-junit-jupiter:3.6.0'

If you are using maven as a build tool then you can use the following pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">




					<source>at least 8</source>
					<target>at least 8</target>

Service Class

The following class defines a method that should save user information but for this example it does nothing.

package com.roytuts.java.junit.mockito.verify;

public class UserService {

    public void saveUser(String userId) {
        System.out.println("Saving user [" + userId + "] info...");

        try {
        } catch (InterruptedException e) {

        System.out.println("User [" + userId + "] info saved");

Junit Class

I am going to write below Junit class under src/test/java folder. In Junit 5 you need to use @ExtendWith and MockitoExtention class. Instead of using actual object I am creating a mock object of UserService class using @Mock annotation.

package com.roytuts.java.junit.mockito.verify;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

public class UserServiceTest {

    private UserService service;

    public void testAutowiredValueField() {
        Mockito.verify(service, Mockito.times(1)).saveUser("1000");


Testing Junit

Running the above Junit test class will give you the successful message and test will be passed.

junit 5 mockito verify

Source Code


Leave a Reply

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