英文:
Mockito.when() clause for java streams
问题
我想知道如何为下面的代码编写when()
子句:
Optional<Adapter> adapterOp = adapters.stream()
.filter(adapter -> adapter.getName().equals(someName))
.findFirst();
英文:
I would like to know how can I write when()
clause for below code
Optional<Adapter> adapterOp = adapters.stream()
.filter(adapter -> adapter
.getName.equals(someName)).findFirst();
答案1
得分: 2
以下是翻译好的部分:
[tag:java-stream] 用于立即数据序列处理,而不作为进一步处理的源。
如果您在单元测试期间需要以某种方式操作Stream,我会坚持以下规则:
- 模拟/伪造一个
List<T>
,从中创建Stream<T>
,或提供其最终输出。 - 模拟/伪造Stream本身中使用的
@FunctionalInterfaces
(Predicate
,Function
等),如果通过类和/或方法传递。 - 单独对处理进行单元测试。
如果您坚持使用Mockito模拟Stream,您需要知道Stream是基于构建器设计模式的流畅接口 - 简而言之,每个方法都返回相同类型的Stream<T>
。这意味着您必须单独模拟链中的每个方法,并返回模拟的Stream<T>
实例的新实例。
英文:
The [tag:java-stream] is used for immediate data sequence processing, not as a source for further processing.
If you need to somehow operate with the Stream during the unit testing, I'd stick with the following rules:
- Mock/fake a
List<T>
from which isStream<T>
created or provide its final output. - Mock/fake the
@FunctionalInterfaces
used in the Stream itself (Predicate
,Function
...) if passed through the class and/or methods. - Unit test the processing itself separately.
If you insist on mocking Stream using Mockito, you have to know that Stream is a fluent interface that is based on the builder design pattern - in nutshell, each method returns the same type Stream<T>
. It means that you have to mock each method of the chain separately and return a new instance of a mocked Stream<T>
instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论