0

How can I compare an array to make sure the expected value is the same as the actual value using Junit Unit Testing in @Test

Here's what I have so far:

@Before

public void initialize() throws Exception{
    bob = new Student(18, "Bob Maher", new String []{"COSC 222","COSC 311", "MATH 200", "MATH 220"});
    bill = new Student(19, "Bill Cosby", new String []{"COSC 222", "COSC 404", "ENGL 112"});
    ben = new Student(24, "Ben Mckenny", new String []{"COSC 222", "COSC 111", "MATH 200", "PHYS 101"});
}

@Test

public void testGetClasses() throws Exception {
    //TODO: test that the classes array returned is correct
    ArrayList<Student> list = new ArrayList<>(Arrays.asList(bob, bill, ben));

    ArrayList<Student> results = Arrays.asList(bob,bill.ben))

    assertTrue(list.containsAll(results) && results.containsAll(list));
}
Seder
  • 2,735
  • 2
  • 22
  • 43
Sentinel
  • 15
  • 5

1 Answers1

4

You can use AssertJ and use either containsExactly() or containsExactlyInAnyOrder(). For example:

String[] expected = { "ABC", "123" };
String[] actual = { "ABC", "234" };
assertThat(actual).containsExactly(expected);

will produce an error:

java.lang.AssertionError: 
Expecting:
  <["ABC", "234"]>
to contain exactly (and in same order):
  <["ABC", "123"]>
but some elements were not found:
  <["123"]>
and others were not expected:
  <["234"]>
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111