How can I assert on a Java Hashmap of Arrays

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m building a new hashmap ( < String , String[] > ) by combining three other hashmaps ( < String , String > ) and adding the filename. How do I assert the new hashmap is correct? The nested array is making the test fail.

This code is a simplified example of my failing test:

@Test
public void injectArrayIntoHashMap() {
  HashMap map = new HashMap();
  map.put("hi", new String[] { "hello", "howdy" });

  HashMap newMap = new HashMap();
  newMap.put("hi", new String[] { "hello", "howdy" });

  assertEquals(map, newMap);
}
  UPDATE:     Okay, based on Hna s advice, I got the test working with an ArrayList.  However, I then realized I needed to instantiate an object inside of the ArrayList and now the test is failing.  It seems to have to do with the fact that the objects inside the ArrayList have different memory addresses.  I m new to Java and inserting the object in the ArrayList this was my attempt to avoid an "if" statement.  Is there a better way?  Or just an easy answer to making my test pass?

Here is the new code:

@Test
public void sampleTest() throws IOException {
  HashMap expectedResult = new HashMap();
  expectedResult.put("/images",                   new ArrayList(Arrays.asList("/images", new Public())));
  expectedResult.put("/stylesheets",              new ArrayList(Arrays.asList("/stylesheets", new Public())));

  HashMap actualResult = test();

  assertEquals(expectedResult, actualResult);
}

public HashMap test() {
  HashMap hashMap = new HashMap();
  hashMap.put("/images",      new ArrayList(Arrays.asList("/images",      new Public())));
  hashMap.put("/stylesheets", new ArrayList(Arrays.asList("/stylesheets", new Public())));
  return hashMap;
}

Answers

This fails because when the assertEquals does the comparison between the arrays it is checking if the memory addresses are equal which obviously fails. One way to solve your problem is to use a container like ArrayList which implements the equals method and can be compared in the way you want.

Here s an example:

public void injectArrayIntoHashMap() {
      HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
      ArrayList<String> l1 = new ArrayList<String>();
      l1.add("hello");
      l1.add("howdy");
      map.put("hi", l1);

      HashMap<String, ArrayList<String>> newMap = new HashMap<String, ArrayList<String>>();
      ArrayList<String> l2 = new ArrayList<String>();
      l2.add("hello");
      l2.add("howdy");
      newMap.put("hi", l2);

      System.out.println(map.equals(newMap));
}

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/18165660/how-can-i-assert-on-a-java-hashmap-of-arrays

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils