0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Hamcrestとは

Posted at

Hamcrestとは

JUnitと一緒に使われることが多いライブラリである
テスト結果の検証(アサーション)を行うときに便利

Hamcrestの特徴

  • 独自のマッチャーを使用してテスト結果を意味のある文章で表現できる
    よってテストコードの可読性が上がりテストの意図が明確となる

Hamcrestのマッチャーの例

  • 文字列
String actualString = "Hello, World!";
assertThat(actualString, containsString("Hello")); // actualStringに"Hello"を含むか検証
assertThat(actualString, startsWith("Hello")); // actualStringが"Hello"で始まるか検証
assertThat(actualString, endsWith("World!")); // actualStringが"World!"で終わるか検証

  • 数値
int actualNumber = 25;
assertThat(actualNumber, greaterThan(20)); // actualNumberが20より大きいか検証
assertThat(actualNumber, lessThanOrEqualTo(35)); // actualNumberが35以下か検証

  • コレクション
List<String> actualList = Arrays.asList("apple", "banana", "orange");
assertThat(actualList, hasSize(3)); // actualListのサイズが3か検証
assertThat(actualList, contains("apple", "banana", "orange")); // actualListが指定した順序で要素を含むか検証
assertThat(actualList, containsInAnyOrder("banana", "orange", "apple")); // actualListが指定した順序を無視して要素を含むか検証

  • オブジェクトのプロパティ
class Person {
    private String name;
    private int age;

    // コンストラクタ、ゲッター、セッターなど
}

Person actualPerson = new Person("Natsu", 25);
assertThat(actualPerson, hasProperty("name", equalTo("Natsu"))); // actualPersonのnameプロパティが"Natsu"か検証
assertThat(actualPerson, hasProperty("age", greaterThan(20))); // actualPersonのageプロパティが20より大きいか検証

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?