To stub void methods to do nothing when invoked, the Stubber interface provides a doNothing method.
package com.example.mokito3.sujan;
public class AppleService {
public void processApple(String appleName) {
System.out.println("I love " + appleName + " 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 static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
@Mock
private AppleService appleService;
@Test
void saveAppleWithStaticMockTest() {
AppleService appleService = mock(AppleService.class);
doNothing().when(appleService).processApple("Macintosh");
appleService.processApple("Macintosh");
}
@Test
void saveAppleWithAnnotationMockTest() {
doNothing().when(appleService).processApple("Macintosh");
appleService.processApple("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()
}