2009-07-06 5 views

答えて

107

のJUnit(および他のテストフレームワーク)とうまく統合し、一致ルールの豊富なセットを提供Hamcrestの使用を示唆(心配しないで、それが出荷されています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")))); 

それが失敗したときに自動的にアサートの適切な説明を取得します。このアプローチを使用します。

+1

オハイオ州、私はhamcrestがjunitディストリビューションにそれを作ったことを認識していませんでした。 Go Nat! – skaffman

+0

私がアイテム( "foo"、 "bar")で構成されているが、他のアイテムが存在しないと主張したいのですが、簡単な構文がありますか? – ripper234

+0

上記のコードスニペットを使用して、追加assertTrue(l.size()== 2) – aberrant80

4

直接、私はあなたがHamcrestコードと共にassertThat()を使用することができるのJUnit 4.4を使用して

+0

これが何らかの理由でコンパイルされません(http://stackoverflow.com/questions/1092981/hamcrests-hasitemsを参照してください): をArrayList 実際=新しいArrayList (); ArrayList expected = new ArrayList (); actual.add(1); expected.add(2); assertThat(実際、hasItems(予想)); – ripper234

2

FEST Fluent Assertionsを見てください。 IMHO彼らは、Hamcrest(そして同様に強力で拡張性のあるもの)より使いやすく、流暢なインターフェイスのおかげでより良いIDEサポートを持っています。 https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions

+0

2017年にはAssertJというFESTの支店を利用している人が増えているようです。 – Max

1

Joachim Sauerの解決策は素晴らしいですが、あなたがすでに結果を確認したいという期待の配列を持っていればうまくいきません。これは、結果を比較したい、あるいは結果にマージされると予想される期待が複数ある場合に、テストで生成済みまたは一定の期待値が既にある場合に発生します。だからではなく、マッチャを使用しての、あなただけの例についてList::containsAllassertTrueを使用することができますすることができます

@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 
} 
関連する問題