Why does Junit prints false for my test?
I am flattening this structure and running Junit5 test against it.
Arrays.asList("a",
Arrays.asList("b",
Arrays.asList("c", "d")), "e")
Junit test:
@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"));
}
Results in error, AssertionFailedError. I see that difference is in whitespaces, and cannot solve this issue.
org.opentest4j.AssertionFailedError:
Expected :[a, b, c, d, e]
Actual :[a, b, c, d, e]
Plain class with static method:
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;
}
}
Aucun commentaire:
Enregistrer un commentaire