Mockito 3 Additional Answers AnswersWithDelay

AdditionalAnswers#AnswersWithDelay method provides a way to return a predefined Answer but with a delay provided.

package com.example.mokito3.sujan;

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

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

import static org.mockito.AdditionalAnswers.answersWithDelay;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {

    @Test
    void saveAppleMockTest() {
        AppleService appleService = mock(AppleService.class);
        when(appleService.saveApple("Macintosh")).thenAnswer(answersWithDelay(1000, InvocationOnMock::getMock));
        System.out.println("apple = " + appleService.saveApple("Macintosh"));
    }
}
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