如何在阵列的Java Hashmap上断言?

时间:2013-08-10 19:37:56

标签: java arrays junit hashmap multidimensional-array

我正在通过组合其他三个哈希映射(< String,String>)并添加文件名来构建新的哈希映射(< String,String []>)。如何断言新的hashmap是否正确?嵌套数组使测试失败。

此代码是我失败测试的简化示例:

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

更新:好的,根据Hna的建议,我让测试使用了ArrayList。但是,我意识到我需要在ArrayList中实例化一个对象,现在测试失败了。这似乎与ArrayList中的对象具有不同的内存地址这一事实有关。我是Java新手并在ArrayList中插入对象,这是我试图避免使用“if”语句。有没有更好的办法?或者只是一个简单的答案让我的测试通过?

这是新代码:

@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;
}

1 个答案:

答案 0 :(得分:4)

这会失败,因为当assertEquals进行数组之间的比较时,它正在检查内存地址是否相等,这显然是失败的。解决问题的一种方法是使用像ArrayList这样的容器来实现equals方法,并且可以按照您想要的方式进行比较。

以下是一个例子:

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));
}
相关问题