更优雅
案例
要在TodoTaskRepository写find方法找到对应task列表,传入自定义的如何find
要传入两个参数,返回一个bool,在文档里找这样的functional interface
java8官方文档-Package java.util.function
BiPredicate是这样的
接口函数是test
public class TodoTaskRepository {
private final List<TodoTask> tasks;
public <T> List<TodoTask> find(T field, BiPredicate<T,TodoTask> filter) {
var tasksFound = new ArrayList<TodoTask>();
for (final TodoTask task : tasks) {
if(filter.test(field, task)) {
tasksFound.add(task);
}
}
return tasksFound;
}
}
单元测试
在find传入的参数中直接实现了接口函数test:(field, task) -> field.equals(task.getID())
|| (field,task)->field.equals(task.getStatus())
@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
public void should_return_task_by_given_id(int givenId) {
// Given
final var todoTaskRepository = new TodoTaskRepository(this.allTasks);
// When
final var taskListFound = todoTaskRepository.find(givenId, ((field, task) -> field.equals(task.getID())));
// Then
assertTrue(taskListFound.size() > 0);
for (final TodoTask taskFound : taskListFound) {
assertEquals(givenId, taskFound.getID());
}
}
@ParameterizedTest
@EnumSource(TodoTaskStatus.class)
public void should_return_task_by_given_status(TodoTaskStatus givenStatus) {
// Given
final var todoTaskRepository = new TodoTaskRepository(this.allTasks);
// When
final var taskListFound = todoTaskRepository.find(givenStatus, (field,task)->field.equals(task.getStatus()));
// Then
assertNotNull(taskListFound);
assertTrue(taskListFound.size() > 0);
for (final TodoTask taskFound : taskListFound) {
assertEquals(givenStatus, taskFound.getStatus());
}
}