Mockito.when()用于Java流的语句

huangapple go评论79阅读模式
英文:

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&lt;Adapter&gt; adapterOp = adapters.stream()
    .filter(adapter -&gt; adapter
    .getName.equals(someName)).findFirst();

答案1

得分: 2

以下是翻译好的部分:

[tag:java-stream] 用于立即数据序列处理,而不作为进一步处理的

如果您在单元测试期间需要以某种方式操作Stream,我会坚持以下规则:

  1. 模拟/伪造一个List<T>,从中创建Stream<T>,或提供其最终输出。
  2. 模拟/伪造Stream本身中使用的@FunctionalInterfacesPredicateFunction等),如果通过类和/或方法传递。
  3. 单独对处理进行单元测试。

如果您坚持使用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:

  1. Mock/fake a List&lt;T&gt; from which is Stream&lt;T&gt; created or provide its final output.
  2. Mock/fake the @FunctionalInterfaces used in the Stream itself (Predicate, Function...) if passed through the class and/or methods.
  3. 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&lt;T&gt;. It means that you have to mock each method of the chain separately and return a new instance of a mocked Stream&lt;T&gt; instance.

huangapple
  • 本文由 发表于 2020年4月6日 20:20:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/61059734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定