doilux’s tech blog

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

Spockで例外をテストするときの注意

例えばこんなメソッドがあって

int convert(String str /* nullかもしれない */ ){
return Optinal.ofNullable(str.length()).orElseThrow( () -> new RuntimeException());
}

Spockのthrownで以下のようなテストをすると通るのでバグに気づかない(NullPointerExceptionはRuntimeExceptionのサブタイプだから)

when:
sut.convert(null)

then:
thrown(RuntimeException)

Spockのthrownを使いたいなら独自RuntimeExceptionを使った方がいいかも。

public class MyAppRuntimeException extends RuntimeException {}