Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit testing on an ArrayList

Suppose that I have the below class, a simple class just to add three Strings into a String ArrayList named ar.

public class Testcases {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

}

public ArrayList<String> myArray()    {
    ArrayList<String> ar = new ArrayList<String>();
    ar.add("Customer1");
    ar.add("Customer2");
    ar.add("Customer3");
    return(ar);
 }
}

How could I use Junit testing to make sure that the Strings actually went into ArrayList?

Update

My TestcasesTest file - where the testing is done, looks as follows:

@Test
public void testMain() {
    System.out.println("main");
    String[] args = null;
    Testcases.main(args);
    // TODO review the generated test code and remove the default call to fail.
    // fail("the test case is a resul in the prototype");
}

/**
 * Test of add method, of class Testcases.
 */
@Test
public void testMyArray() {
    assertEquals(Arrays.asList("Customer1", "Customer2", "Customer3"), myArray());
}

}
like image 847
cs_guy Avatar asked Jan 18 '26 14:01

cs_guy


1 Answers

Following code should do :

@Test
public void myArrayTest()    {
    TestCases testCases = new TestCases();
    List<String> result = testCases.myArray();
    Assert.assertNotNull("List shouldn't be null", result);
    Assert.assertEquals("wrong size", 3, result.size());
    Assert.assertEquals("Wrong 1st element", "Customer1", result.get(0));
    Assert.assertEquals("Wrong 2nd element", "Customer2", result.get(1));
    Assert.assertEquals("Wrong 3rd element", "Customer3", result.get(2));
}
like image 81
realUser404 Avatar answered Jan 20 '26 02:01

realUser404



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!