JUnit5 测试扁平化 ArrayList 结果为 false

JUnit5 testing flattened ArrayList results in false

为什么 Junit 测试显示 AssertEquals 对于我的测试是错误的?

我正在展平这个结构并运行 Junit5 测试它。

Arrays.asList("a", 
    Arrays.asList("b",
        Arrays.asList("c", "d")), "e")

联合测试:

@Test
public void shouldFlattenAListOfList() throws Exception {
    List<String> flatten = Problem07.flatten(Arrays.asList("a", Arrays.asList("b",
            Arrays.asList("c", "d")), "e"), String.class);
    assertEquals(flatten.size(), 5);
    System.out.println(flatten == Arrays.asList("a", "b", "c", "d", "e")); // prints: false
    assertEquals(flatten, Arrays.asList("a", "b", "c", "d", "e"));
}

结果出错,AssertionFailedError。我看到区别在于空格,无法解决此问题。

org.opentest4j.AssertionFailedError: 
Expected :[a,  b,  c,  d,  e]
Actual   :[a, b, c, d, e]

使用静态方法的普通 class:

public class Problem07 {
    static List<String> flatten(Collection<?> objects, Object aClass) {
        if (objects == null) {
            throw new NoSuchElementException();
        }

        if (objects.isEmpty()) {
            return Collections.emptyList();
        }

        List<String> strings = new ArrayList<>();

        /*TODO generify for other classes, not only hardcoded String*/
        objects.forEach(o -> {
            if (o instanceof ArrayList) {
                ArrayList<String> o1 = (ArrayList<String>) o;
                strings.addAll(o1);
            } else {
                strings.add(o.toString());
            }
        });

        String formattedString = strings.toString()
                .replace("[", "")  //remove the right bracket
                .replace("]", "");  //remove the left bracket

        List<String> list = new ArrayList<>(Arrays.asList(formattedString.split(",")));

        System.out.println(list);//prints: [a,  b,  c,  d,  e]

        return list;
    }
}

您通过调用 List.toString() 获得的 formattedString 将由于默认 toString() 格式而在元素之间引入额外的 space。这意味着您的扁平化列表将包含 "a"、"b"、"c"、...而不是 "a"、“b”、“c”、.. . 显然 String "b" 不等于 String " b".

您不应该依赖 toString()split() 来获得扁平化列表。您可以破解它以删除表面的 spaces,但最好使用递归遍历 objects 集合中的每个嵌套级别。

我相信您展平阵列的方式不推荐您这样做。您正在使用 strings.toString() 获取字符串,然后从中删除括号。我建议使用 recursion 作为 flattening 列表。在这里,我使用递归修改了您的代码。

static List<String> flatten(Collection<?> objects, Object aClass) {
        if (objects == null) {
            throw new NoSuchElementException();
        }
        if (objects.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> strings = new ArrayList<>();
        objects.forEach(o -> {
            if (o instanceof List) {
                strings.addAll(flatten((List)o,String.class));
            } else {
                strings.add(o.toString());
            }
        });
        return strings;
    }

还有一个建议,请不要使用 == 来检查逻辑相等性,而是使用 equals