UserService implements Queryable<User> { @Override public QueryResult<User> query(final Query<User> query) { final String roleField = "roles"; final xyz.morphia.query.Query<User> q = this.datastore.createQuery(User.class); if (query.doFilter()) { final List<String> roles = query.getFilters().get(roleField); final List<String> batchIds = query.getFilters().get("batchid"); if (roles != null) { q.field(roleField).hasAllOf(new ArrayList<>(roles)); } if (batchIds != null) { q.field("batchId").equal(batchIds.get(0)); } } final FindOptions options = new FindOptions(); if (query.doPaginate()) { options.limit(query.getPageSize()); options.skip(query.getPageNumber() * query.getPageSize()); } final long total = q.count(); final List<User> ret = q.asList(options); return new QueryResult<>(query, ret, (int) total); } @Inject  UserService(final Datastore datastore, final IdGenerator idGenerator,
      final KafkaUserService kafkaService); List<User> getAll(); User saveNewEntity(final User user); void updateEntity(final User user); Optional<User> getEntityById(final String id); void deleteEntityById(final String id); Optional<User> findEntityByFieldValue(final String field, final Object value); @Override QueryResult<User> query(final Query<User> query);  }
@Test public void testPaginationFull() { final int usersTotal = 13; final int pageLen = 6; final int pageIndex = 1; this.fillUsers(usersTotal); final MultivaluedHashMap<String, String> paginationParams = new MultivaluedHashMap<>(); paginationParams.add("page[number]", "" + pageIndex); paginationParams.add("page[size]", "" + pageLen); final Query<User> paginationQuery = Query.fromParameterMap(paginationParams); final xyz.morphia.query.Query<User> q = Mockito.mock(xyz.morphia.query.Query.class); Mockito.when(this.store.createQuery(User.class)).thenReturn(q); Mockito.doAnswer(new Answer<List<User>>() { @Override public List<User> answer(final InvocationOnMock invocation) throws Throwable { final FindOptions options = invocation.getArgument(0, FindOptions.class); final int skip = options.getSkip(); final int limit = options.getLimit(); final List<User> r = new ArrayList<>(UserServiceTest.this.users.subList(skip, skip + limit)); return r; } }).when(q).asList(ArgumentMatchers.any(FindOptions.class)); final QueryResult<User> returned = this.userService.query(paginationQuery); Assert.assertEquals(pageLen, returned.getN()); }