1

I got an error when I tried to test 2 ArraysLists. It seems the error is saying "toArray() is undefined" at my removeEndWith_at method. Could you guys give me an advice how to test these 2 ArraysList?

Thanks.

Java version: 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;
    }

}

[ArrayListIteratorTest Class]

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());
    }

}

arccycle
  • 83
  • 1
  • 2
  • 11

2 Answers2

3

Look at the

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

Arrays.asList()

method just creates a wrapper around the original elements and on this wrapper are not implemented methods which changes its size.

Also look at my implementation of method removeEndWith_at. It is simpler than yours version

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

When comparing two instances of List<String> using Jupiter Assertion API, give assertLinesMatch a try.

Sormuras
  • 8,491
  • 1
  • 38
  • 64