AssertJ withComparatorForFields не работает при сравнении двух объектов с полями в разном порядкеJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 AssertJ withComparatorForFields не работает при сравнении двух объектов с полями в разном порядке

Сообщение Anonymous »

У меня есть два объекта, которые отличаются только порядком значений event.entityId.
Фактическое:

Код: Выделить всё

ChangeStatusRequest(action=update,  recipient=recipient(recipientId=5, recipientType=test), entity=entity(entityId=5011,5001, entityType=type1), orderParams=OrderParams(advancedMode=null, orders=[Orders(sId=5, info=[info(inEntityId=5011, entityType=type1), info(inEntityId=5001, entityType=type1)])], sId=null), events=null)
Ожидается:

Код: Выделить всё

ChangeStatusRequest(action=update, recipient=recipient(recipientId=5, recipientType=test), entity=entity(entityId=5001,5011, entityType=type1), orderParams=OrderParams(advancedMode=null, orders=[Orders(sId=5, info=[info(inEntityId=5001, entityType=type1), info(inEntityId=5011, entityType=type1)])], sId=null), events=null)
Чтобы сравнить их, я использую AssertJ с '.withComparatorForFields'

Код: Выделить всё

        assertThat(actual).usingRecursiveComparison().withComparatorForFields(comparator, "entityId").ignoringCollectionOrder()
.ignoringActualNullFields()
.isEqualTo(expected);
Я пишу собственный компаратор для сравнения идентификатора объекта

Код: Выделить всё

    class StringIgnoringOrderComparator implements Comparator {
@Override
public int compare(String s1, String s2) {
if (s1 == null || s2 == null) {
return s1 == s2 ? 0 : -1; // Handle nulls
}

// Split the strings into arrays, trim spaces, and sort
String[] parts1 = Arrays.stream(s1.split(","))
.map(String::trim)
.sorted()
.toArray(String[]::new);

String[] parts2 = Arrays.stream(s2.split(","))
.map(String::trim)
.sorted()
.toArray(String[]::new);
// Compare the sorted arrays as strings
return Arrays.equals(parts1, parts2) ? 0 : -1;
}
}
Но во время утверждения у меня возникла ошибка

Код: Выделить всё

field/property 'entity.entityId' differ:
- actual value  : "5011,5001"
- expected value: "5001,5011"

The recursive comparison was performed with this configuration:
- all actual null fields were ignored in the comparison
- no overridden equals methods were used in the comparison (except for java types)
- collection order was ignored in all fields in the comparison
- these types were compared with the following comparators:
- java.lang.Double -> DoubleComparator[precision=1.0E-15]
- java.lang.Float -> FloatComparator[precision=1.0E-6]
- java.nio.file.Path -> lexicographic comparator (Path natural order)
- these fields were compared with the following comparators:
- entityId -> com.Test$StringIgnoringOrderComparator@426792b1
- field comparators take precedence over type comparators.
- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior).
- the introspection strategy used was: DefaultRecursiveComparisonIntrospectionStrategy
Почему компаратор не сработал? как мне это исправить?

Подробнее здесь: https://stackoverflow.com/questions/793 ... -fields-in
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»