Issue
I am trying to test below Vote.java which has a method called isEligibleToVote() which in turn calls
another method getResult() after a check. I am trying to capture the argument and assert but while doing so I am getting Wanted but not invoked: vote.getResult(<Capturing argument>);
I understand this is because of vote.isEligibleToVote(18);
as I have declared vote using @Mock which is incorrect, but I don't know how can I test this class using ArgumentCaptor and verify methods.
Vote.java
public class Vote {
public void isEligibleToVote(int age){
if(age>18)
getResult("yes");
else
getResult("no");
}
public String getResult(String result){
return result;
}
}
VoteTest.java
@ExtendWith(MockitoExtension.class)
public class VoteTest {
@Mock
Vote vote;
@Test
public void isEligibleToVote_test(){
ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
vote.isEligibleToVote(18);
verify(vote).getResult(stringArgumentCaptor.capture());
assertEquals("yes", stringArgumentCaptor.getValue());
}
}
Error Staacktrace
Wanted but not invoked:
vote.getResult(<Capturing argument>);
-> at VoteTest.isEligibleToVote_test(VoteTest.java:24)
However, there was exactly 1 interaction with this mock:
vote.isEligibletoVote(18);
-> at VoteTest.isEligibleToVote_test(VoteTest.java:23)
Wanted but not invoked:
vote.getResult(<Capturing argument>);
-> at VoteTest.isEligibleToVote_test(VoteTest.java:24)
However, there was exactly 1 interaction with this mock:
vote.isEligibletoVote(18);
-> at VoteTest.isEligibleToVote_test(VoteTest.java:23)
at VoteTest.isEligibleToVote_test(VoteTest.java:24)
I understand vote is mock, but I want to know how can I call vote.iseligibleTovote(18) and get the arguments of getResult from inside if and else condition
Solution
Use @Spy
instead of @Mock
to do the verification. You must call when()
on any methods of a mocked object which you aren't doing hence the wanted but not invoked
Answered By - tomgeraghty3