【问题标题】:How to eliminate the trailing white space after an ArrayList? [duplicate]如何消除 ArrayList 之后的尾随空格? [复制]
【发布时间】:2025-12-05 21:00:01
【问题描述】:

我正在尝试创建一个断言两个 ArrayList 相等的测试。运行测试时,我收到一个错误,即预期和实际之间存在一个差异:arraylist 末尾有一个空格。

问题不是由arraylist内部的任何东西引起的,问题是在arraylist关闭之后。据我所知,在 java 中没有用于此的修剪功能,也没有忽略空格的 junit 测试。

ArrayList<Quote> expected = new ArrayList<>();

        Quote q1 = new Quote("Test Test", "This is a quote.");
        Quote q2 = new Quote("Author Two", "Quote 2.");
        Quote q3 = new Quote("Unknown", "This quote does not have an author.");
        Quote q4 = new Quote("Author Three-three", "Quote 3.");

        expected.add(q1); expected.add(q2); expected.add(q3); expected.add(q4);

这给我的是:java.util.ArrayList_

(我在空格处加了下划线)

我期望的是:java.util.ArrayList

这不包括空格。

我不知道为什么我会得到空格,也不知道如何摆脱它。任何帮助将不胜感激。

更多上下文,整个测试器文件

public class ImportQuotesTest {

    BufferedReader reader;
    @Before
    public void setUp() throws Exception {
        File file = new File("C:\\Users\\homba\\Documents\\QuotesProject\\src\\ImportQuotesTest.txt");

        reader = new BufferedReader(new FileReader(file));
    }

    @Test
    public void fillList() throws IOException {
        ArrayList<Quote> actual = ImportQuotes.fillList(reader);
        ArrayList<Quote> expected = new ArrayList<>();

        Quote q1 = new Quote("Test Test", "This is a quote.");
        Quote q2 = new Quote("Author Two", "Quote 2.");
        Quote q3 = new Quote("Unknown", "This quote does not have an author.");
        Quote q4 = new Quote("Author Three-three", "Quote 3.");

        expected.add(q1); expected.add(q2); expected.add(q3); expected.add(q4);

        Assert.assertEquals(expected,actual);
    }
}```

【问题讨论】:

  • 您没有显示实际打印或比较您的列表的代码。那看起来像什么?
  • 我只是使用 Assert.assertEquals() 将两者作为对象进行比较,就像java Assert.assertEquals(expected,actual);
  • edit问题并在那里添加所有相关代码。 Java 不会神奇地添加空格,因此您的测试中一定有一些东西。尝试提供minimal reproducible example
  • ...文件的内容是什么?您的问题可能在ImportQuotes.fillList(reader) 内部。

标签: java unit-testing arraylist junit


【解决方案1】:

啊,是的,我偶然发现了一次!首先,如果您正在进行单元测试,只需遍历整个列表并断言每个元素或自己构建一个字符串。我想我在日食中看到了这一点。它以某种方式运行自己的 junit 版本,我认为在命令行中从 mvn test 运行时测试通过了。

简短回答您的问题:

  1. 如果可以,您可以使用 Hamcrest:Assert about a List in Junit

  2. 迭代: for (int i = 0; i&lt; list1.size; i++) { assertEquals(list1.get(i), list2.get(i)); }

  3. StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); list1.forEach(sb1::append); list2.forEach(sb1::append); assertEquals(sb1.toString(), sb2.toString()

首选方式是数字 1 或 3。

【讨论】:

  • 是的,你是对的,这个测试从命令行通过,只有在我使用 Intellij 时才会失败。很高兴我没有做错什么。谢谢!
  • 你不应该接受这个答案,这是一个黑客,你也不应该以这种方式比较数组。如果有的话,试试Assert.assertArrayEquals
  • @x80486 assertArrayEquals 将不起作用,因为这是一个 List 对象而不是数组。原来的 assertEquals 应该可以工作。
  • assertEquals 最终只运行对象的equals(在本例中为ArrayList)。这与比较两个toString()s 有着根本的不同。我不确定你的Quote 类的equals 是如何实现的,但如果比较正确,那么我敢打赌你的报价确实不同(即使它们看起来相等)。如果您遍历它们并分别比较它们,您的测试是否成功?
  • 当您遍历两个列表时,最好使用the Iterator。在 ArrayList 上调用 .get() 并不算太糟糕,但在 LinkedList 上调用 .get() 这样的效率非常低。
最近更新 更多