Search code examples
javaunit-testingasserthamcrestassertthat

How to use AssertThat to check the property value of objects in a list?


I am to using asserThat to verify properties of objects in an ArrayList.

I am able to use assertThat if none of the objects contains data to be tested but I am not able to figure how to use assertThat if only one of the objects contain data to be tested.

Sample Code:

public class dataNeeded {
    String data;
    String modifiedDate;

    public String getData(){
         return data;
    }
    ......
}

public ArrayList<dataNeeded> returnsNeededData(){
 ...
}

List<dataNeeded> dataToBeTested = returnsNeededData();
dataToBeTested.forEach(data->assertThat(data.getData(), not(equalTo("No"))));

List<dataNeeded> dataToBeTested2 = returnsNeededData();
// I need to verify if one of the objects in this list has it's data as "No" 
dataToBeTested.forEach(data->assertThat(data.getData(), ???);

Solution

  • You can map to List<String> via the following function (uses Java 8 Streams) to extract all data strings

    private List<String> mapToDataStrings(List<dataNeeded> neededData) {
        return neededData.stream()
                .map(dataNeeded -> dataNeeded.getData())
                .collect(toList());
    }
    

    and then use the everyItem/hasItem function in Matchers to make assertions on the resulting list of strings:

    List<String> dataToBeTested = mapToDataStrings(returnsNeededData());
    assertThat(dataToBeTested, everyItem(not("No")));
    
    List<String> dataToBeTested2 = mapToDataStrings(returnsNeededData());
    assertThat(dataToBeTested2, hasItem("No"));
    

    With everyItem you can assert that every element in the list is not "No" and hasItem asserts that there is at least one element in the list with value "No".


    Alternatively you could implement a feature matcher to avoid the mapping function.