Inserting material into a Map <?,?> Or converting a map <String, String> to a map <?,?>

I, unfortunately, come across an interface that is defined using the following

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

I am trying to write unit tests that consume this interface.

 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); 

and the compiler works.

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

If I try to use pageMaps directly, it tells me:

 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>) 

If I do pageMaps a Map<?,?> , I cannot put lines in it.

 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) 

I saw some client code that does ugly unchecked conversions like

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

How to get data in Map<?,?> Or convert my Map<String,String> to Map<?,?> ?

+4
source share
1 answer
  • You cannot write Map<String, String> map = getMap("abc"); without broadcast
  • The problem has more to do with easymock and the types returned and expected by the expect and andReturn methods that I am not familiar with. You can 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); 

Not sure if this can be mixed with your ridicule. This might work:

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

Also note that you cannot add anything to the general collection using the template. So:

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

will not compile if a and b do not matter.

+5
source

All Articles