Mockito 3 Timeout

Mocktio framework provides a timeout method, which makes sure that the desired mocked method has been invoked for a given number of times within the time limit.

Mockito#timeout in async mode will keep on checking over and over multiple times to check whether verify is a success or not till the given amount of millisecond passed or verification is a success.
once verify is success Mockito#timeout will exit the method call without waiting for the amount of millisecond to complete.

package com.example.mokito3.sujan;

public class AppleService {
    public String saveApple(String apple) {
        System.out.println("i love " + apple + " apple");
        return apple;
    }
}
package com.example.mokito3.sujan;

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

import java.time.Duration;
import java.time.Instant;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Mock
    private AppleService appleService;


    @Test
    void saveAppleWithStaticMockTest() throws InterruptedException {
        AppleService appleService = mock(AppleService.class);
        when(appleService.saveApple("Macintosh")).thenReturn("i have apple");
        Instant start = Instant.now();
        appleService.saveApple("Macintosh");
        Thread.currentThread().sleep(5000);
        appleService.saveApple("Macintosh");
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to run method " + timeElapsed.toMillis() + " milliseconds");
        verify(appleService, timeout(1000).atLeast(2)).saveApple("Macintosh");
        end = Instant.now();
        timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to complete test case " + timeElapsed.toMillis() + " milliseconds");
    }

    @Test
    void saveAppleWithAnnotationMockTest() throws InterruptedException {
        when(appleService.saveApple("Macintosh")).thenReturn("i have apple");
        Instant start = Instant.now();
        appleService.saveApple("Macintosh");
        Thread.currentThread().sleep(5000);
        appleService.saveApple("Macintosh");
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to run method " + timeElapsed.toMillis() + " milliseconds");
        verify(appleService, timeout(1000).atLeast(2)).saveApple("Macintosh");
        end = Instant.now();
        timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to complete test case " + timeElapsed.toMillis() + " milliseconds");
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
}
test {
    useJUnitPlatform()
}

Timeout in multithreaded environment

Mockito timeout will work in a multi-threaded environment as well.

package com.example.mokito3.sujan;

import java.util.concurrent.TimeUnit;

public class AppleService {
    public String saveApple(String apple) throws InterruptedException {
        System.out.println("i love " + apple + " apple");
        return apple;
    }
}
package com.example.mokito3.sujan;

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

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    @Mock
    private AppleService appleService;

    @Test
    void saveAppleWithStaticMockTest() throws InterruptedException {
        AppleService appleService = mock(AppleService.class);
        when(appleService.saveApple("Macintosh")).thenReturn("i have apple");
        Instant start = Instant.now();
        appleService.saveApple("Macintosh");
        runWithMultiThread(appleService, "Macintosh");
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to run method " + timeElapsed.toMillis() + " milliseconds");
        verify(appleService, timeout(10000).atLeast(5)).saveApple("Macintosh");
        end = Instant.now();
        timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to complete test case " + timeElapsed.toMillis() + " milliseconds");
    }

    @Test
    void saveAppleWithAnnotationMockTest() throws InterruptedException {
        AppleService appleService = mock(AppleService.class);
        when(appleService.saveApple("Macintosh")).thenReturn("i have apple");
        Instant start = Instant.now();
        appleService.saveApple("Macintosh");
        runWithMultiThread(appleService, "Macintosh");
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to run method " + timeElapsed.toMillis() + " milliseconds");
        verify(appleService, timeout(10000).atLeast(5)).saveApple("Macintosh");
        end = Instant.now();
        timeElapsed = Duration.between(start, end);
        System.out.println("Time taken: to complete test case " + timeElapsed.toMillis() + " milliseconds");
    }

    void runWithMultiThread(AppleService appleService, String appleName) {
        IntStream.rangeClosed(1, 5).forEach(i -> executorService.execute(() -> {
            try {
                appleService.saveApple(appleName);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
        executorService.shutdown();
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
}
test {
    useJUnitPlatform()
}

follow us on