Skip to content

Commit

Permalink
Fix Mockito do-syntax (#274)
Browse files Browse the repository at this point in the history
* Fix do-syntax in tests

* Fix do-syntax handling in MockitoWhen
  • Loading branch information
martinmladenov authored Jul 22, 2024
1 parent 1c0e05e commit 7788b3a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,12 @@ public boolean visit(MethodInvocation mi) {
* If the method call just after when() matches the one we are expecting, bingo!
*/
if(inWhenMode) {
if(methodToSetUp.equals(methodName) || methodToSetUp.equals(previousMethodName)) {
if(methodToSetUp.equals(methodName) ||
methodToSetUp.equals(previousMethodName) && allowedDoInvocations.contains(methodName)) {
numberOfCallsToWhen++;
inWhenMode = false;
previousMethodName = "";
} else if(notInDoWhenOrNoMatch(methodName)){
inWhenMode = false;
previousMethodName = "";
} else {
previousMethodName = methodName;
}
inWhenMode = false;
previousMethodName = "";
} else {
/**
* We wait for a call to when().
Expand All @@ -70,12 +66,7 @@ public boolean visit(MethodInvocation mi) {
}
return super.visit(mi);
}
private boolean notInDoWhenOrNoMatch(String methodName){
return !methodName.equals("when")
&&
(allowedDoInvocations.contains(previousMethodName)
|| !allowedDoInvocations.contains(methodName));
}

@Override
public boolean result() {
return comparison.compare(numberOfCallsToWhen, expectedNumberOfOccurrences);
Expand Down
22 changes: 18 additions & 4 deletions andy/src/test/resources/codechecker/fixtures/MockitoWhenCalls.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ void t2() {
void t3(){
List<String> mockedList = mock(List.class);
Mockito.doThrow(IllegalArgumentException.class).when(mockedList).toString();
doNothing().when(mockedList.size());
doNothing().when(mockedList).size();
doReturn("2").when(mockedList).get(any(Integer.class));

verify(mockedList, times(2)).toString();
Expand All @@ -46,9 +46,9 @@ void t3(){
@Test
void t4(){
List<String> mockedList = mock(List.class);
Mockito.doNothing().when(mockedList.size());
doReturn("2").when(mockedList.get(any(Integer.class)));
doReturn("3").when(mockedList.remove(any(Integer.class)));
Mockito.doNothing().when(mockedList).size();
doReturn("2").when(mockedList).get(any(Integer.class));
doReturn("3").when(mockedList).remove(any(Integer.class));

verify(mockedList, times(1)).remove(1);
verify(mockedList, times(1)).remove(2);
Expand All @@ -57,4 +57,18 @@ void t4(){
verify(mockedList, times(1)).get(5);
}

@Test
void t5(){
List<String> mockedList = mock(List.class);
Mockito.doReturn(3).when(mockedList).size();
mockedList.get(3);
}

@Test
void t6(){
List<String> mockedList = mock(List.class);
Mockito.doReturn(3).when(mockedList.get(3));
mockedList.get(3);
}

}

0 comments on commit 7788b3a

Please sign in to comment.