概要
Truth 1.2.0で新しくisWithin().of()
が追加されたので使い方のメモです。
例えば、あるメソッドが戻り値として期待される整数値に非常に近い値を返すかをテストしたい場合、assertThat
メソッドを使って対象の値を指定し、isWithin
メソッドで許容範囲を設定し、of
メソッドで期待値を指定します。
ここで、actualValue
はテスト対象の値、tolerance
は許容される差の範囲、expectedValue
は期待される値を指します。
assertThat(actualValue).isWithin(tolerance).of(expectedValue)
具体例
具体例だとこんな感じです。
assertThat(20000).isWithin(0).of(20000) // OK 20000±0の範囲に期待される値が入る
assertThat(20000).isWithin(1).of(20000) // OK 20000±1の範囲に期待される値が入る
assertThat(20000).isWithin(10000).of(20000) // OK 20000±10000の範囲に期待される値が入る
assertThat(20000).isWithin(10000).of(30000) // OK 20000±10000の範囲に期待される値が入る
assertThatIsWithinFails(20000, 9999, 30000) // NG 20000±9999の範囲に期待される値が入らない
assertThatIsWithinFails(20000, 10000, 30001) // NG 20000±10000の範囲に期待される値が入らない
関連リンク
isWithin().of()
を追加するコミットに含まれてるテストコードはこちら。
https://github.com/google/truth/commit/6464cb5ca#diff-6bb9d1ff6594320c37d2edc59edcf4dcd390dc9c6f6f926bac12c5363c2dbff4