将内容放入Map<?,?>中或将Map<String,String>转换为Map<?,?>

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<?,?> ?


这里有点混淆:你试图说服编译器,stupid是一个具有2个类型参数(你不关心的)的Map,但是,你仍然在类型Map<String,String>中使用了Map。但是你应该做的是测试接口是否适用于你需要的任何类型组合。 - Ingo
如果你让它返回 pageMaps,会发生什么?EasyMock.expect(config.getMap("sillyMap")).andReturn(pageMaps); - JB Nizet
我只关心它在这个测试中作为Map<String,String>的形式,但这并不重要。如果我无法将数据放入其中,我就看不出如何“测试接口是否适用于我需要的任何类型组合”。如果我使地图完全通用,put()会拒绝工作。 - Visionary Software Solutions
@JBNizet 这就是我所说的“当我试图直接使用pageMaps时”的意思。 - Visionary Software Solutions
1个回答

5
  1. There is no way you can write Map<String, String> map = getMap("abc"); without a cast
  2. The problem has more to do with easymock and the types returned/expected by the expect and andReturn methods, which I'm not familiar with. You could write

    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都为空,否则无法编译。


做得好,我没有想过尝试在expect调用中进行类型转换。 - Visionary Software Solutions

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接