OnJava8-Examples/verifying/CountedListTest.java

87 lines
2.4 KiB
Java
Raw Normal View History

// verifying/CountedListTest.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Simple use of JUnit to test CountedList.
package verifying;
2015-06-15 17:47:35 -07:00
import java.util.*;
2016-08-23 12:33:38 -06:00
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
2015-06-15 17:47:35 -07:00
public class CountedListTest {
private CountedList list;
2016-08-23 16:48:02 -06:00
@BeforeEach
public void initialize() {
list = new CountedList();
System.out.println("Set up for " + list.getId());
2015-06-15 17:47:35 -07:00
for(int i = 0; i < 3; i++)
list.add(Integer.toString(i));
2015-06-15 17:47:35 -07:00
}
2016-08-23 16:48:02 -06:00
@AfterEach
public void cleanup() {
System.out.println("Cleaning up " + list.getId());
2015-06-15 17:47:35 -07:00
}
// All tests are marked with the @Test annotation:
@Test
public void insert() {
System.out.println("Running testInsert()");
2015-06-15 17:47:35 -07:00
assertEquals(list.size(), 3);
list.add(1, "Insert");
assertEquals(list.size(), 4);
assertEquals(list.get(1), "Insert");
}
@Test
public void replace() {
System.out.println("Running testReplace()");
2015-06-15 17:47:35 -07:00
assertEquals(list.size(), 3);
list.set(1, "Replace");
assertEquals(list.size(), 3);
assertEquals(list.get(1), "Replace");
}
// A helper method to reduce code duplication. As long
// as it isn't annotated with @Test, it will not
// be automatically executed by JUnit.
private
void compare(List<String> lst, String[] strs) {
String[] array = lst.toArray(new String[0]);
2016-08-23 16:48:02 -06:00
assertTrue(array.length == strs.length,
"Arrays not the same length");
2015-06-15 17:47:35 -07:00
for(int i = 0; i < array.length; i++)
assertEquals(strs[i], array[i]);
}
@Test
public void order() {
System.out.println("Running testOrder()");
2015-06-15 17:47:35 -07:00
compare(list, new String[] { "0", "1", "2" });
}
@Test
public void remove() {
System.out.println("Running testRemove()");
2015-06-15 17:47:35 -07:00
assertEquals(list.size(), 3);
list.remove(1);
assertEquals(list.size(), 2);
compare(list, new String[] { "0", "2" });
}
@Test
public void addAll() {
System.out.println("Running testAddAll()");
2015-06-15 17:47:35 -07:00
list.addAll(Arrays.asList(new String[] {
"An", "African", "Swallow"}));
assertEquals(list.size(), 6);
compare(list, new String[] { "0", "1", "2",
"An", "African", "Swallow" });
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
CountedList #0
Running testAddAll()
CountedList #1
Running testInsert()
CountedList #2
Running testRemove()
CountedList #3
Running testOrder()
CountedList #4
Running testReplace()
2015-09-07 11:44:36 -06:00
*/