Last active
December 4, 2020 12:19
-
-
Save sachi-d/9b35c769865b72813e234dae3f141df6 to your computer and use it in GitHub Desktop.
Mockito verify examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Animal { | |
boolean amIBird; | |
public Animal(boolean amIBird) { | |
this.amIBird = amIBird; | |
} | |
public void move(int distance) { | |
boolean isBird = amIBird(); | |
if (isBird) { | |
fly(distance); | |
} else { | |
doNotFly(); | |
} | |
} | |
public boolean amIBird() { | |
return amIBird; | |
} | |
public void fly(int distance) { | |
System.out.println("I am flying"); | |
for (int i = 0; i < distance; i++) { | |
flapWings(); | |
} | |
} | |
public void flapWings() { | |
System.out.println("Flapping wings"); | |
} | |
public void doNotFly() { | |
System.out.println("I am not flying"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import junit.framework.TestCase; | |
import org.junit.Before; | |
import org.junit.Test; | |
import org.mockito.InOrder; | |
import org.mockito.Mockito; | |
import static org.mockito.Mockito.*; | |
public class ParrotTest extends TestCase { | |
private Animal parrot; | |
@Before | |
public void setUp() { | |
parrot = new Animal(true); | |
} | |
@Test | |
public void testInvocationOfMethod() { | |
Animal mockedParrot = Mockito.spy(parrot); | |
mockedParrot.move(2); | |
//verify the number of invocations | |
verify(mockedParrot, times(1)).amIBird(); | |
verify(mockedParrot, times(1)).fly(2); | |
verify(mockedParrot, never()).doNotFly(); | |
} | |
@Test | |
public void testOrderOfMethods() { | |
Animal mockedParrot = Mockito.spy(parrot); | |
mockedParrot.move(1); | |
//verify the order of invocations | |
InOrder inOrder = Mockito.inOrder(mockedParrot); | |
inOrder.verify(mockedParrot).amIBird(); | |
inOrder.verify(mockedParrot).fly(1); | |
inOrder.verify(mockedParrot).flapWings(); | |
} | |
@Test | |
public void testLeastMaxNumberOfInvocations() { | |
Animal mockedParrot = Mockito.spy(parrot); | |
mockedParrot.move(3); | |
verify(mockedParrot, atLeast(1)).flapWings(); | |
verify(mockedParrot, atMost(5)).flapWings(); | |
} | |
@Test | |
public void testNoInvocations() { | |
Animal mockedParrot = Mockito.spy(parrot); | |
parrot.move(3); //Note that this is parrot, not the 'mockedParrot' | |
verifyNoMoreInteractions(mockedParrot); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment