Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Java 8 streams?

list.stream().forEach(e -> { dbCall.delete(e.Id());});

Each item from the list is deleted from the database.

Assuming there were 3 items in the list, how to unit test:

  1. Delete was called 3 times.
  2. Delete was called 'in order/sequence', i.e. sequence of elements in the list?
like image 301
Tanvi Jaywant Avatar asked Jun 13 '18 10:06

Tanvi Jaywant


2 Answers

You can use JUnit's InOrder.

DbCall dbCall = mock(DbCall.class);
List<Element> list = Arrays.asList(newElement(1), newElement(2), newElement(3));

runDeleteMethod(list);

InOrder inorder = inOrder(dbCall);
inorder.verify(dbCall).delete(1);
inorder.verify(dbCall).delete(2);
inorder.verify(dbCall).delete(3);
like image 91
daniu Avatar answered Oct 08 '22 15:10

daniu


Just verify the expected time dbCall.delete() should be called. This can look like this:

Mockito.verify(dbCall, times(3L)).delete(any(String.class));

Streams can work parallel and so you can´t verify the the sequence. You can do it with verify element on index but the sequence will be ignored. Mockito will just verify the call+value was used. That´s enought for a unit-test.

like image 25
LenglBoy Avatar answered Oct 08 '22 16:10

LenglBoy