简体   繁体   中英

How do I test an ArrayList in jUnit?

I have a list of numbers and I'm trying to write a jUnit test that checks to make sure the list is being populated and returned correctly. I'm running into a problem where I can't figure out how to write the correct jUnit test. Here's what I come up with:

ArrayListPractice.java

import java.util.ArrayList;

public class ArrayListPractice {
    ArrayList<String> myList = new ArrayList<String>();

    public ArrayList<String> addToList(String item) {
        myList.add(item);
        return myList;
    }

    public ArrayList<String> printList(ArrayList<String> myList) {
        for (String currentString : myList) {
            System.out.println(currentString);
        }
        return myList;
    }
}

ArrayListPracticeTest.java

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ArrayListPracticeTest {
    ArrayList<String> myList = new ArrayList<>();
    ArrayListPractice alp;

    @Before
    public void setUp() throws Exception {
        alp = new ArrayListPractice();
        alp.addToList("ONE");
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testPrintList() {
        String expected = "ONE";
        ArrayList<String> actual = alp.printList(myList);
        assertEquals("not the correct list", expected, actual);
    }
}

While I have deep reservations over the quality of this code, the problem is that you're not comparing apples to apples here. You expect a String , but you're getting back an ArrayList . Thus, the test fails with a false positive; you didn't set the test up correctly

The fix is to ensure that what you expect is what you actually get back.

final ArrayList<String> expected = Arrays.asList("ONE");

Now, to fix the actual code, I encourage you to get rid of the parameter. I leave that as an exercise for the reader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM