doilux’s tech blog

ITに関する備忘録。 DDP : http://doiluxng.hatenablog.com/entry/2018/01/01/195409

EnumのテストはStreamApiを使う

こんなクラスがあったとき

public enum Vehicle {
    BIKE(false),
    MOTOR_CYCLE(true),
    CAR(true);

    private final boolean needLicence;

    Vehicle(boolean b) {
        needLicence = b;
    }

    @Override
    public String toString() {
        return this.name();
    }

    public boolean isNeedLicence() {
        return needLicence;
    }
}

こんなテストの書き方をしていると

@Unroll
class VehicleTest extends Specification {

    def "#sut needs licence : #result"() {
        expect:
        sut.isNeedLicence() == result

        where:
        sut                 || result
        Vehicle.BIKE        || false
        Vehicle.MOTOR_CYCLE || true
        Vehicle.CAR         || true
    }
}

ENUMが増えた時にテストコードもメンテしないといけない。

    AIR_PLANE(false); // bug

なので、こうします。

    def "isNeedLicence"() {
        setup:
        def notNeedLicenceList = [Vehicle.BIKE]
        def needLicenceList = Stream.of(Vehicle.values()).filter {
            !notNeedLicenceList.contains(it)
        }.collect(Collectors.toList())


        expect:
        notNeedLicenceList.stream().filter { it.isNeedLicence() }.collect(Collectors.toList()).size() == 0
        needLicenceList.stream().filter { !it.isNeedLicence() }.collect(Collectors.toList()).size() == 0
    }

免許がいらない乗り物が増えた時はメンテがいるけど、逆に免許がいる乗り物のときはメンテがいらないですし、乗り物増えてもコード量が増えないのがいいですね。