JUnit5测试flattened ArrayList导致false

时间:2018-04-17 17:27:41

标签: java list junit5

为什么Junit测试告诉我,我的测试中AssertEquals是假的?

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

"dependencies": {
    "@angular/animations": "^4.1.3",
    "@angular/cdk": "^2.0.0-beta.12",
    "@angular/common": "^4.1.3",
    "@angular/compiler": "4.1.3",
    "@angular/core": "4.1.3",
    "@angular/forms": "4.1.3",
    "@angular/http": "4.1.3",
    "@angular/material": "^2.0.0-beta.12",
    "@angular/platform-browser": "4.1.3",
    "@angular/platform-browser-dynamic": "4.1.3",
    "@angular/router": "4.1.3",
    "@angular/upgrade": "4.1.3",
}

Junit测试:

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

导致错误,AssertionFailedError。我发现差异在于空白,无法解决这个问题。

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

使用静态方法的普通类:

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

2 个答案:

答案 0 :(得分:3)

通过调用formattedString获得的List.toString()会因默认toString()格式化而在元素之间引入额外空格。这意味着代替&#34; a&#34;,&#34; b&#34;,&#34; c&#34;,...您的展平列表将包含包含&#34; a&#34 ;,&#34; b&#34;,&#34; c&#34;,......显然是String&#34; b&#34;不等于String&#34; B&#34;

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

答案 1 :(得分:3)

我相信你扁平化阵列的方式不建议做那个工作。您正在使用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