代码之家  ›  专栏  ›  技术社区  ›  codebot

为Java8流编写单元测试

  •  1
  • codebot  · 技术社区  · 7 年前

    我有一个列表,我正在对该列表进行流式处理,以获得一些过滤数据,如下所示:

    List<Future<Accommodation>> submittedRequestList = 
        list.stream().filter(Objects::nonNull)
                     .map(config -> taskExecutorService.submit(() -> requestHandler
                     .handle(jobId, config))).collect(Collectors.toList());
    

    当我编写测试时,我尝试使用 when()

    List<Future<Accommodation>> submittedRequestList = mock(LinkedList.class);
    when(list.stream().filter(Objects::nonNull)
                      .map(config -> executorService.submit(() -> requestHandler
                                .handle(JOB_ID, config))).collect(Collectors.toList())).thenReturn(submittedRequestList);
    

    我要走了 org.mockito.exceptions.misusing.WrongTypeOfReturnValue: LinkedList$$EnhancerByMockitoWithCGLIB$$716dd84d cannot be returned by submit() 当() ?

    1 回复  |  直到 7 年前
        1
  •  6
  •   daniu    7 年前

    您只能模拟单个方法调用,而不能模拟整个fluent接口级联。

    Stream<Future> fs = mock(Stream.class);
    when(requestList.stream()).thenReturn(fs);
    Stream<Future> filtered = mock(Stream.class);
    when(fs.filter(Objects::nonNull).thenReturn(filtered);
    

    等等

    在我看来,这真的不值得嘲笑整件事,只要验证所有过滤器都被调用并检查结果列表的内容就行了。