【问题标题】:How can I assert on a Java Hashmap of Arrays?如何在数组的 Java Hashmap 上断言?
【发布时间】:2013-08-10 19:37:55
【问题描述】:

我正在通过组合其他三个哈希图( )并添加文件名来构建一个新的哈希图( )。如何断言新的 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;
}

【问题讨论】:

    标签: java arrays junit hashmap multidimensional-array


    【解决方案1】:

    这失败了,因为当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));
    }
    

    【讨论】:

    • 非常感谢!工作完美。我总是回避 ArrayLists(我是 Java 新手)。我想我应该开始更多地使用它们。哦,谢谢你的代码。这很有帮助,因为我对如何构建 ArrayList 和插入数据感到困惑。
    • 嗨,海娜。这是有效的,然后我遇到了一个问题。我现在插入一个字符串和对象(一个实例化的类)的数组列表,而不是插入一个字符串数组列表。而且它失败了。 :o( 有什么想法吗?
    • 你能举个例子吗?钥匙的类型是什么?值的类型是什么?
    • 非常感谢,海娜!我在原始线程中发布了更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多