我如何在 JUnit5 中测试列表?

how could I test Lists in JUnit5?

我尝试测试 2 个 ArraysList 时出错。 似乎错误是在我的 removeEndWith_at 方法中说 "toArray() is undefined"。你们能给我一个如何测试这两个 ArraysList 的建议吗?

谢谢。

Java版本:jdk-10.0.2
JUnit:5

[ArrayListIterator Class]

import java.util.Iterator;
import java.util.List;

public class ArrayListIterator {

    /**
     * @param wordsAl : list of words
     */
    public List<String> removeEndWith_at(List<String> wordsAl) {
        Iterator<String> iterator = wordsAl.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().endsWith("at"))
                iterator.remove();
        }

        return wordsAl;
    }

}

[ArrayListIteratorTestClass]

import static org.junit.Assert.assertArrayEquals;

import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;

class ArrayListIteratorTest {

    ArrayListIterator alIterator = new ArrayListIterator();
    List<String> actualWords = Arrays.asList("Apple", "Bat", "Orange", "Cat");

    @Test
    void testremoveEndWith_at() {
        actualWords = alIterator.removeEndWith_at(actualWords);
        List<String> expectedvalue = Arrays.asList("Apple", "Orange");
        assertArrayEquals(expectedvalue.toArray(), actualWords.toArray());
    }

}

看看

remove() on List created by Arrays.asList() throws UnsupportedOperationException

Arrays.asList()

方法只是在原始元素周围创建一个包装器,并且在这个包装器上没有实现改变其大小的方法。

另请看我的实现方法removeEndWith_at。它比你的版本更简单

        /**
     * @param wordsAl : list of words
     */
    public List<String> removeEndWith_at(List<String> wordsAl) {
            wordsAl.removeIf(s -> s.endsWith("at"));
            return wordsAl;
    }

使用 Jupiter 断言 API 比较 List<String> 的两个实例时,请尝试 assertLinesMatch