JUnitの中CollectionAssert?
質問
のNUnitの CollectionAssert
のにJUnitの平行はありますか?
解決
あなたは Hamcrest のコード(心配しないでください、それはに同梱されていますと一緒にassertThat()
を使用することができるのJUnit 4.4を使用しますJUnitの、複雑な自己記述を生成するために余分な.jar
は必要)のコレクションで動作するものも含めてアサートません。
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;
List<String> l = Arrays.asList("foo", "bar");
assertThat(l, hasItems("foo", "bar"));
assertThat(l, not(hasItem((String) null)));
assertThat(l, not(hasItems("bar", "quux")));
// check if two objects are equal with assertThat()
// the following three lines of code check the same thing.
// the first one is the "traditional" approach,
// the second one is the succinct version and the third one the verbose one
assertEquals(l, Arrays.asList("foo", "bar")));
assertThat(l, is(Arrays.asList("foo", "bar")));
assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));
これが失敗したときに自動的にアサートの適切な説明を取得します。このアプローチを使用します。
他のヒント
未直接、ありません。私は Hamcrest に、JUnitのとうまく統合されたルールに一致するの豊富なセットを提供している(とその他の使用を提案しますテストフレームワーク)
FEST流暢アサーションを見てみましょう。私見彼らは流れるようなインターフェイスのおかげで(拡張可能など、と同じように強力な)Hamcrestよりも使用することがより便利で、より優れたIDEをサポートしています。 https://github.com/alexruiz/fest-を参照してください。
をフェスト・アサーションを使用して主張-2.xの/ウィキ/ヨアヒム・ザウアーのソリューションはいいですが、あなたはすでにあなたの結果であることを確認したいの期待の配列を持っている場合は動作しません。あなたはすでにあなたに結果を比較したいあなたのテストで生成されるか、または一定の期待を持っている、または多分あなたが結果にマージされることを期待する複数の期待を持っているとき、これが出てくるかもしれません。だからではなく、マッチャを使用してのあなただけの例についてList::containsAll
とassertTrue
を使用することができます:
@Test
public void testMerge() {
final List<String> expected1 = ImmutableList.of("a", "b", "c");
final List<String> expected2 = ImmutableList.of("x", "y", "z");
final List<String> result = someMethodToTest();
assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK
assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK
assertTrue(result.containsAll(expected1)); // works~ but has less fancy
assertTrue(result.containsAll(expected2)); // works~ but has less fancy
}
所属していません StackOverflow