0

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?

Makoto
  • 104,088
  • 27
  • 192
  • 230
Phreakradio
  • 176
  • 1
  • 18
  • 1
    Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Do not give 50% code and explain what the other code is supposedly doing. If your assumptions about your code were all correct, there wouldnt be a problem, right. SO: give us something that is complete enough to repro the issue! – GhostCat Jan 23 '19 at 19:48
  • [Why are you using `peek` at all in this fashion?](https://stackoverflow.com/q/33635717/1079354) Using `map` to map across each `CMService` object as deleted, then collecting that result in a set would be ***better*** than using a part of the API which isn't intended to be used by typical consumer applications. – Makoto Jan 23 '19 at 20:13

1 Answers1

2

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.

user268396
  • 11,576
  • 2
  • 31
  • 26