我有像这样的Java 8 Predicate。如何为此
编写单元测试 Predicate<DTO> isDone = (dtO) ->
(!dto.isFinished() &&
!dto.isCompleted());
由于
答案 0 :(得分:2)
如果您有对谓词的引用(如您的示例中所示),那么我看不出任何问题。以下是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);
}
答案 1 :(得分:2)
我会像那样测试:
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;
}
}
而不是a
,s
和f
将测试命名为:should_be_done_when_it_is_both_finished_and_completed
。
我认为DTO
只是一个值对象,所以我宁愿创建真实实例而不是使用mock。