Johnboll
Johnboll

Reputation: 55

Is it possible to initialize a mock with when() inside a java stream

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

Answers (2)

jannis
jannis

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

Oliver Gondža
Oliver Gondža

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

Related Questions