Phreakradio
Phreakradio

Reputation: 186

Testing method with variable made using Stream...peek()

I've set up a Mockito test class to test out a method that generates a variable using Java 8 Streams. Essentially, it is a collection of objects (currentTr) that have an isDeleted property. This is the line that generates that variable.

FPTR = Stream.of(currentTR)
        .peek(CMService::markAsDeleted)
        .collect(Collectors.toSet();

When run normally, it runs just fine. Objects in that collection are set as deleted.

The issue is that when I run my test cases, this variable does not contain any objects set for deletion (in other word, it seems either the peek() or the method specified (markAsDeleted) is never called).

I've thought of using when().thenCallRealMethod(), however, given that markAsDeleted is a void method, I'm getting an error that won't allow me to do that either. Error being:

when(cmservice.markAsDeleted(anyObject())).thenCallRealMethod();

java: 'void' type not allowed here

I've mocked up the CMService in the test field as such:

@Mock
CMService cmservice;

Is there a way to trigger the method call in .peek() so that I get the right variable at all or is it a setup issue?

Upvotes: 0

Views: 649

Answers (1)

user268396
user268396

Reputation: 11976

The reason you cannot use when() to set up things is because for that to work the mocked method must return something. However there is also a "reversed" API/syntax to do what you want using for example:

doCallRealMethod().when(cmservice).markAsDeleted()

See the documentation. There's more. The most generic is the doAnswer() method.

Upvotes: 2

Related Questions