Tanvi Jaywant
Tanvi Jaywant

Reputation: 415

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?

Upvotes: 5

Views: 10874

Answers (2)

LenglBoy
LenglBoy

Reputation: 1441

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.

Upvotes: 1

daniu
daniu

Reputation: 14999

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);

Upvotes: 4

Related Questions