Reputation: 65
I have a Java 8 Predicate like this. How do I write unit test for this
Predicate<DTO> isDone = (dtO) ->
(!dto.isFinished() &&
!dto.isCompleted());
Thanks
Upvotes: 2
Views: 13857
Reputation: 1533
I would test it like that:
private final Predicate<DTO> isDone = (dto) ->
(!dto.isFinished() && !dto.isCompleted());
@Test
public void a() throws Exception {
// given
DTO dto = new DTO(true, true);
// when
boolean result = isDone.test(dto);
// then
assertThat(result).isFalse();
}
@Test
public void s() throws Exception {
// given
DTO dto = new DTO(true, false);
// when
boolean result = isDone.test(dto);
// then
assertThat(result).isFalse();
}
@Test
public void d() throws Exception {
// given
DTO dto = new DTO(false, true);
// when
boolean result = isDone.test(dto);
// then
assertThat(result).isFalse();
}
@Test
public void f() throws Exception {
// given
DTO dto = new DTO(false, false);
// when
boolean result = isDone.test(dto);
// then
assertThat(result).isTrue();
}
@AllArgsConstructor
public static class DTO {
private final boolean isFinished;
private final boolean isCompleted;
public boolean isFinished() {
return isFinished;
}
public boolean isCompleted() {
return isCompleted;
}
}
Instead of a
, s
, and f
name the tests properly like: should_be_done_when_it_is_both_finished_and_completed
.
I suppose DTO
is just a value object so I'd rather create real instance instead of using mock.
Upvotes: 4
Reputation: 12021
If you have a reference to the predicate (as it seems in your example) then I see no issues. Here is simple example with Mockito/JUnit:
@Mock
private DTO mockDTO;
@Test
public void testIsDone_Finished_NotComplete()
{
when(mockDTO.isFinished()).thenReturn(true);
when(mockDTO.isCompleted()).thenReturn(false);
boolean expected = false;
boolean actual = isDone.test(mockDTO);
Assert.assertEquals(expected, actual);
}
Upvotes: 2