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

标签 java junit

在将 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/

相关文章:

java - 对于旋转 View ,执行(点击())在 espresso ui 测试中不起作用

java - 如何在给定执行时间的情况下每隔固定时间调用方法

java - session 变量在第一次请求后变为空

java - 一个方法在 JUnit 中生成了预期的结果,但它说它是 null

java - @Before 和 @Transactional

java - 使用 BufferedReader 检测用户的特定输入

java - 如何从java桌面应用程序代码打开新的浏览器窗口?

android - 如何在 junit 测试中模拟用户点击 ListView 项?

java - 无法实例化 @InjectMocks 字段

spring - 运行集成测试时无法加载 ApplicationContext