Reputation: 55
I am writing a test where i have a set which will be put in to a method. I will then mock the method so it always returns return true.
I want to be able do this with help of a stream, so i can have a large Set. I am using JUnit4 for testing and Mockito for mocking.
Example:
setWithValues.stream().map(value-> when(method.returnTrueOrFalse(value)).thenReturn(true));
Upvotes: 0
Views: 261
Reputation: 5210
Another way:
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
(...)
Mockito.doAnswer(i -> setWithValues.contains(i.getArgument(0)))
.when(method)
.returnTrueOrFalse(ArgumentMatchers.any());
Upvotes: 2
Reputation: 3511
While I can only speculate what the problem is with the code, my guess is the mocking is never executed for the absence of a terminal operation, it feels just wrong. The thing is it introduces new stubbing for every value in your set. Consider following alternative:
when(method.returnTrueOrFalse(Mockito.argThat(org.hamcrest.collection.IsIn.isIn(setWithValues)))).thenReturn(true);
// Or with static imports
when(method.returnTrueOrFalse(argThat(isIn(setWithValues)))).thenReturn(true);
It will aid debugability and will scale better with your set growing larger.
Upvotes: 4