简体   繁体   English

模拟java8 stream.map

[英]Mocking java8 stream.map

I am using mockito how can I mock stream.map() call. 我正在使用Mockito我该如何模拟stream.map()调用。

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. 我正在寻找一种正确的模拟方法,该方法将在输出中返回“ upperCaseStream”。

Keep in mind that the identity of method references or lambdas is not guaranteed to be the same even if the calls look identical. 请记住,即使调用看起来相同,也不保证方法引用或lambda的标识相同。 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. 我对Mockito不太了解,但是我相信它会检查是否存在一个值, when注册时,这可能会调用对equals的调用,而该调用不保证在此处无法正常工作。 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") 顺便说一句,我真的不明白为什么需要模拟Stream<String> ,在那里您可以简单地执行Stream.of("foo","bar")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM