We have created a mock object using Mock
, its working fine, but we need to make sure that Mock
method is actually called. for this, Mockito provides the Verify method.
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 static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class AppleServiceTest {
@Test
void saveAppleWithMockTest() {
AppleService appleService = mock(AppleService.class);
appleService.saveApple("Macintosh");
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()
}
Mocktio verify
method has lot of overloaded constructor. Mockito provides VerificationMode
interface which is used to calculate the number of times stub methods has been invoked. VerificaitonMode
is also an input parameter in verify
method, if we dont provide any then VerificationMode.times(1)
will be default.
verify(appleService).saveApple("Macintosh") is equal to verify(appleService, times(1)).saveApple("Macintosh")
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.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
@Mock
private AppleService appleService;
@Test
void saveAppleWithStaticMockTest() {
AppleService appleService = mock(AppleService.class);
appleService.saveApple("Macintosh");
verify(appleService).saveApple("Macintosh");
verify(appleService, times(1)).saveApple("Macintosh");
}
@Test
void saveAppleWithAnnotationMockTest() {
appleService.saveApple("Macintosh");
verify(appleService).saveApple("Macintosh");
verify(appleService, times(1)).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()
}