gpt4 book ai didi

java - JUnit AssertEquals() 由于数组上存在额外空格而失败

转载 作者:行者123 更新时间:2023-12-01 19:50:43 26 4
gpt4 key购买 nike

在将 2 个数组与其中的 kafka 生产者记录进行比较时,我的 Junit 测试失败了。失败的原因是数组后面多了一个空格。

预期:

java.util.ArrayList<[ProducerRecord(topic=producer-test, partition=null, 
headers=RecordHeaders(headers = [], isReadOnly = false), key=0,
value=Message: test-message,
Number: 0, timestamp=null), ProducerRecord(topic=producer-test,
partition=null, headers=RecordHeaders(headers = [], isReadOnly = false),
key=1, value=Message: test-message,
Number: 1, timestamp=null)]>

实际:

java.util.ArrayList<[ProducerRecord(topic=producer-test, partition=null, 
headers=RecordHeaders(headers = [], isReadOnly = false), key=0,
value=Message: test-message,
Number: 0, timestamp=null), ProducerRecord(topic=producer-test,
partition=null, headers=RecordHeaders(headers = [], isReadOnly = false),
key=1, value=Message: test-message,
Number: 1, timestamp=null)]>

IDE 告诉我,唯一的区别是 Expected 中 arrayList 末尾后面有一个空格,您可以通过突出显示末尾来看到这一点。这是怎么回事?!

编辑:

这是一些其他代码

List<ProducerRecord<Integer, TestObj>> history = producer.history();

//To be inserted into expected
TestObj obj0 = new TestObj("test-message", 0);
TestObj obj1 = new TestObj("test-message", 1);

//new arraylist is needed or else the lists have slightly different types for some reason
List<ProducerRecord<Integer, TestObj>> expected = new ArrayList<ProducerRecord<Integer, TestObj>>(Arrays.asList(
new ProducerRecord<Integer, TestObj>("producer-test", 0, obj0),
new ProducerRecord<Integer, TestObj>("producer-test", 1, obj1)
));

Assert.assertEquals("Sent didn't match expected!", expected, history);

最佳答案

Assert.assertEquals() 正在调用 expected.equals(history)

List.equals(Object o) 的定义如下:

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

您是否为 ProducerRecord 类定义了 equals 方法?

如果没有,那么您的 ProducerRecord 对象将通过引用相等进行比较,这意味着它们只会在它们实际上是相同的对象的基础上进行比较。由于您正在测试中构造新的 ProducerRecord 对象,因此它们不会具有引用相等性。

关于java - JUnit AssertEquals() 由于数组上存在额外空格而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com