Avinash Kharche
Avinash Kharche

Reputation: 441

Mock chain calls involves Stream in Java

How can I mock chained calls with streams,. Also notice that it is calling each.getName() as an intermediate operation. I cannot create SomeCountobject so have to mock it also.

Set<String> obj = new HashSet<String>();
List<SomeCount> someGroups = Some_Mocked_Implementation();
obj = someGroups.stream().map(each -> each.getName()).filter(each -> 
                          userNames.indexOf(each) == -1)
                         .collect(Collectors.toSet());

Upvotes: 3

Views: 1075

Answers (1)

GhostCat
GhostCat

Reputation: 140447

You don't.

This is classical "input/output" testing only. You simply want to create an input list that contains specific objects, so that you can predict what should come out of that operation.

In other words, your test should in essence look like:

assertThat(someMethodDoingTheStreamOperation(yourInputList), is(expectedResult));

Mocking containers, such as List or Map is (almost always) wrong.

If you still insist on doing it, you could be using Mockito and its deep stubs support.

But again: that means that you start putting implementation details of your solution into your test code. This means that your test code is nothing but a "copy" of your production code. The second you change your production code, your unit test might break. So even simple refactoring might become a problem.

You always prefer to have tests that do not rely on mocking. And when talking about lists, then hey: fill a list with prepared input, instead of mocking the list.

Upvotes: 3

Related Questions