Почему тест 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]
Обычный класс со статическим методом:
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;
}
}




Ваш formattedString, полученный при вызове List.toString(), добавит дополнительное пространство между элементами из-за форматирования toString() по умолчанию. Это означает, что вместо «a», «b», «c», ... ваш плоский список будет содержать «a», «b», «c», ... и, очевидно, строка «b» будет не равно Строке «b».
Вы не должны полагаться на toString() и split(), чтобы получить сплющенный список. Вы можете взломать его, чтобы удалить поверхностные пробелы, но было бы лучше использовать рекурсию для итерации по каждому уровню вложенности в коллекции 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.