3

I am using mockito how can I mock stream.map() call.

I tried something like this which return null.

@Mock Stream<String> stringStream;
@Mock Stream<String> upperCaseStream;

when(stringStream.map(String::toUpperCase)).thenReturn(upperCaseStream);
syso(stringStream.map(String::toUpperCase));

This prints null.

I am looking for a correct way of mocking that would return 'upperCaseStream' in output.

Manipal
  • 195
  • 3
  • 7
  • Have you actually initialized `upperCaseStream`? – Turing85 May 19 '16 at 22:26
  • I have initialized the mocks that's not the problem. Without initialization stringStream.map(String::toUpperCase) would throw NPE. – Manipal May 19 '16 at 22:27
  • These are simple, heavily-tested library functions. Why are you trying to mock them? – Jeff Bowman May 19 '16 at 22:38
  • 1
    What exactly are you trying to do here? This sounds like a [XY question](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Tunaki May 19 '16 at 22:39
  • 3
    Don't. Just don't mock these things. They aren't meant to be mocked. Use real values, if small toy ones. But this is the kind of thing you shouldn't be mocking in the first place. – Louis Wasserman May 19 '16 at 23:10
  • I understand that using test data is the right way to go, but wanted to know if mocking was the only option what effort would it take. – Manipal May 19 '16 at 23:18

1 Answers1

4

Keep in mind that the identity of method references or lambdas is not guaranteed to be the same even if the calls look identical. Check this out

I don't know much about Mockito, but I believe it checks if there exists a value that a when registered, this might invlove a call to equals somewhere which is not guranteed to work here. For example:

Function<String, String> fn1 = String::toUpperCase;
Function<String, String> fn2 = String::toUpperCase;
System.out.println(fn1.equals(fn2)); // false on my machine

You can simply store the reference in a variable and use it later on

Function<String, String> toUpperCase = String::toUpperCase;
when(stringStream.map(toUpperCase)).thenReturn(upperCaseStream);

System.out.println(stringStream.map(toUpperCase));

Btw, I really don't understand why would ever need to mock Stream<String> where you can simply do Stream.of("foo","bar")

Community
  • 1
  • 1
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
  • 2
    "Identity of method references or lambdas is not guaranteed to be the same even if the calls look identical". This explains why my approach is failing. Thanks. – Manipal May 19 '16 at 23:20