5

ユニットテストでハムクレスト付きのjunitを使用していますが、ジェネリックスの問題が発生しました。


assertThat(collection, empty());

この方法では型推論が利用できないことを認識しており、解決策の1つは型ヒントを提供することですが、静的インポートを使用する場合、どのように型推論を行う必要がありますか?

4

2 に答える 2

3

型推論は私たちが望むほど強力ではありませんが、この場合、実際に問題があるのはAPIです。それは正当な理由もなくそれ自体を不必要に制限します。is-emptyマッチャーは、特定ののコレクションだけでなく、任意のコレクションで機能しますE

APIがこのように設計されていると仮定します

public class IsEmptyCollection implements Matcher<Collection<?>>
{
    public static Matcher<Collection<?>> empty()
    {
        return new IsEmptyCollection();
    }
}

その後assertThat(list, empty())、期待どおりに動作します。

APIを変更するように作成者を説得することができます。その間あなたはラッパーを持つことができます

@SuppressWarnings("unchecked")
public static Matcher<Collection<?>> my_empty()
{
    return (Matcher<Collection<?>>)IsEmptyCollection.empty();
}
于 2011-07-30T23:09:12.813 に答える
0

私はその問題をよく理解していません。私が使用する方法は次のとおりです。

/**
 * A matcher that returns true if the supplied {@link Iterable} is empty.
 */
public static Matcher<Iterable<?>> isEmpty() {
    return new TypeSafeMatcher<Iterable<?>>() {

        @Override
        public void describeTo(final Description description) {
            description.appendText("empty");
        }

        @Override
        public boolean matchesSafely(final Iterable<?> item) {
            return item != null && !item.iterator().hasNext();
        }
    };
}

そして、私はそれを次のように使用します:

List<String> list = new ArrayList<String>();
assertThat(list, isEmpty());

ここではジェネリックに問題はありません。

于 2011-07-30T23:31:01.040 に答える