简体   繁体   中英

Writing unit tests for Java 8 streams

I have a list and I'm streaming this list to get some filtered data as:

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

When I wrote tests, I tried to return some data using a 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);

I'm getting org.mockito.exceptions.misusing.WrongTypeOfReturnValue: LinkedList$$EnhancerByMockitoWithCGLIB$$716dd84d cannot be returned by submit() error. How may I resolve this error by using a correct when() ?

You can only mock single method calls, not entire fluent interface cascades.

Eg, you could do

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

and so on.

IMO it's really not worth mocking the whole thing, just verify that all filters were called and check the contents of the result list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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