Mockito 3 Reset Mock

Each Mockito test case target a specific edge case and consists of a mock or @Mock, verify method, and asserts if taking the help of JUnit.

For every new test input data, it's recommended to create a new test case, keep test case small and focused.

Please keep test case small & focused on a single behavior

Incorporating multiple test cases input in 1 test case only is a poor coding practice, but if required after every test case we can reset existing data and test again.

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

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

    @Test
    void saveAppleWithoutMockTest() {
        when(appleService.saveApple("Macintosh")).thenReturn("i eat apple");
        String macApple = appleService.saveApple("Macintosh");
        assertEquals("i eat apple", macApple);
        verify(appleService).saveApple("Macintosh");
        reset(appleService);
        when(appleService.saveApple("Fuji")).thenReturn("i love apple");
        String fujiApple = appleService.saveApple("Fuji");
        assertEquals("i love apple", fujiApple);
        verify(appleService).saveApple("Fuji");
    }
}
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()
}

 

It is advised to hardly use reset() feature because it could be a sign of poor tests. in the normal test case, it doesn't need to reset the mocks but to create a new mock for each test input.

Instead of using reset() feature, consider writing a simple, small, and focused test methods. Using reset() signifies that a lot of inputs are being tested in a single test case.

follow us on