我有一个这样的Java8谓词。我如何为此编写单元测试?
Predicate<DTO> isDone = (dtO) ->
(!dto.isFinished() &&
!dto.isCompleted());谢谢
发布于 2016-12-13 16:21:18
我会这样测试它:
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;
}
}将测试命名为:should_be_done_when_it_is_both_finished_and_completed,而不是a、s和f。
我认为DTO只是一个值对象,所以我宁愿创建真实的实例,而不是使用模拟。
发布于 2016-12-13 14:35:52
如果您有对谓词的引用(就像在您的示例中一样),那么我认为没有问题。以下是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);
}https://stackoverflow.com/questions/41112267
复制相似问题