4

私は不幸なことに、誰かが次のように定義したインターフェースを扱っています

public Map<?, ?> getMap(String key);

このインターフェイスを使用する単体テストを作成しようとしています。

Map<String,String> pageMaps = new HashMap<String,String();
pageMaps.put(EmptyResultsHandler.PAGEIDENT,"boogie");
pageMaps.put(EmptyResultsHandler.BROWSEPARENTNODEID, "Chompie");
Map<?,?> stupid = (Map<?, ?>)pageMaps;
EasyMock.expect(config.getMap("sillyMap")).andReturn(stupid);

そしてコンパイラは退屈しています。

The method andReturn(Map<capture#5-of ?,capture#6-of ?>) in the type IExpectationSetters<Map<capture#5-of ?,capture#6-of ?>> is not applicable for the arguments (Map<capture#7-of ?,capture#8-of ?>)

pageMaps直接使用しようとすると、次のように表示されます。

The method andReturn(Map<capture#5-of ?,capture#6-of ?>) in the type IExpectationSetters<Map<capture#5-of ?,capture#6-of ?>> is not applicable for the arguments (Map<String,String>)

を作成pageMapsするMap<?,?>と、その中に文字列を入れることができません。

The method put(capture#3-of ?, capture#4-of ?) in the type Map<capture#3-of ?,capture#4-of ?> is not applicable for the arguments (String, String)

次のような、醜い未チェックの変換を行うクライアント コードを見てきました。

@SuppressWarnings("unchecked")
        final Map<String, String> emptySearchResultsPageMaps = (Map<String, String>) conf.getMap("emptySearchResultsPage");

Map<?,?>データを に取得したり、データを に変換Map<String,String>したりするにはどうすればよいMap<?,?>ですか?

4

1 に答える 1

5
  1. Map<String, String> map = getMap("abc");キャストなしで書く方法はありません
  2. 問題は、私がよく知らないeasymock と メソッドによって返される/期待される型にもっと関係していexpectます。andReturnあなたは書くことができます

    Map<String, String> expected = new HashMap<String, String> ();
    Map<?, ?> actual = getMap("someKey");
    boolean ok = actual.equals(pageMaps);
    //or in a junit like syntax
    assertEquals(expected, actual);
    

それがあなたのモッキングと混在できるかどうかはわかりません。これはおそらくうまくいくでしょう:

EasyMock.expect((Map<String, String>) config.getMap("sillyMap")).andReturn(pageMaps);

また、ワイルドカードを使用してジェネリック コレクションに何も追加できないことにも注意してください。したがって、この:

Map<?, ?> map = ...
map.put(a, b);

abが nullでない限り、コンパイルされません。

于 2013-02-24T10:21:22.607 に答える