Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

java - How can I make a Hamcrest assert? It should ask that a list of items has a property which is in an other list?

Ok, i have a database which gets filled up with random objects type of MandantEntity. I have a finder, which finds items by a given array of ids. I would like to check if the returned list has all the items (ids), that I ask for (ids array) so i thought to do it like the following:

@Test
public void testFindById() {
    long[] ids = new long[10];
    for (int j = 0; j < ids.length; j++) {
        long l = ids[j];
        MandantEntity mandantEntity = getMandant(j);
        MandantEntity save = mandantRepository.save(mandantEntity);
        ids[j] = save.getId();
    }


    final List<MandantEntity> entities = mandantRepository.findById(ids);

    assertTrue(entities.size() == ids.length);
    assertThat(entities, contains(hasProperty("id", contains(ids))));

}

but does not work...

java.lang.AssertionError: Expected: iterable containing [hasProperty("id", iterable containing [[<1L>, <2L>, <3L>, <4L>, <5L>, <6L>, <7L>, <8L>, <9L>, <10L>]])] but: item 0: property 'id' was <1L>

I have no idea how to arrange this. Have anyone an Idea ?

Greetings Jens

question from:https://stackoverflow.com/questions/65626730/how-can-i-make-a-hamcrest-assert-it-should-ask-that-a-list-of-items-has-a-prope

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way to do this is to pass a List of Matchers to contains:

List<Matcher<Object>> expected = Arrays.stream(ids)
    .mapToObj(id -> hasProperty("id", equalTo(id)))
    .collect(Collectors.toList());

assertThat(entities, contains(expected));

If you plan to do this a lot, you can put it in a helper method:

private static <E> Matcher<Iterable<? extends E>> containsWithProperty(String propertyName, List<?> propertyValues) {
    List<Matcher<? super E>> itemMatchers = propertyValues.stream()
        .map(value -> hasProperty(propertyName, equalTo(value)))
        .collect(Collectors.toList());

    return contains(itemMatchers);
}

Usage:

// Convert ids array to a List
List<Long> idList = Arrays.stream(ids)
    .boxed()
    .collect(Collectors.toList());

assertThat(entities, containsWithProperty("id", idList));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...