Mockito 3 Clear Invocations

Mockito keeps tracks of methods arguments and invocation count so that it can be further asserted, but if required we can clear all invocation of mocked instance. Mockito provides Mockito#clearInvocations. It is a very controversial method and must be avoided, Only if memory issue or unable to efficiently test then only it should be used.

it's advised to avoid this feature at all costs. Use this feature only  if unable to efficiently test the program.

package com.example.mokito3.sujan;

public abstract 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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

    @Test
    void saveAppleWithMockTest() {
        when(appleService.saveApple("Macintosh")).thenReturn("i eat apple");
        appleService.saveApple("Macintosh");
        clearInvocations(appleService);
        verify(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