user10977476
user10977476

Reputation:

How to change if and for to assert in the test

This test verifies the correctness of the method that transport planes receive from the list of military planes. As in the test not to use "for" and "if", and to use an assertTrue. Also can not use FLAG and lambda. Next to all this should be one Assert.

@Test
public void testGetTransportMilitaryPlanes() {
    Airport airport = new Airport(planes);
    List<MilitaryPlane> transportMilitaryPlanes = airport.getTransportMilitaryPlanes();

    boolean flag = false;
    for (MilitaryPlane militaryPlane : transportMilitaryPlanes) {
        if ((militaryPlane.getMilitaryType() == MilitaryType.TRANSPORT)) {
            flag = true;
            break;
        }
    }
    Assert.assertEquals(flag, true);
}

I did so:

@Test
public void testGetTransportMilitaryPlanes() {
    Airport airport = new Airport(planes);
    List<MilitaryPlane> transportMilitaryPlanes = airport.getTransportMilitaryPlanes();

    MilitaryPlane militaryPlane = (MilitaryPlane) transportMilitaryPlanes;
    Assert.assertTrue(militaryPlane.getMilitaryType() == MilitaryType.TRANSPORT);

}

But the test fails like that. And in the original version was true.

Upvotes: 0

Views: 148

Answers (1)

Mureinik
Mureinik

Reputation: 312146

Using streams would make this much more elegant:

Assert.assertTrue
    (transportMilitaryPlanes.stream()
                            .anyMatch(p -> p.getMilitaryType() == MilitaryType.TRANSPORT));

Upvotes: 4

Related Questions