Home > Software engineering >  Why does my array not fill with null when it gets created?
Why does my array not fill with null when it gets created?

Time:12-20

I am an AP cs student and we are doing a lab to help us get practice working with arrays. However, I am haveing a problem with a particular test for one of my methods. The method is supposed to take a list of names in an array and turn them into their initial form. For example: Kent, Clark would be turned into KC. I have this part down however one of the tests doesn't seem to work. This is my code:

public String[] initialsArray() {
    String[] initials = new String[numberActive];
    for (int i = 0; i < initials.length; i  ) {
        initials[i] = ""   names[i].charAt(names[i].indexOf(",")   2)  
                names[i].charAt(0);
    }
    return initials;
}

numberActive signifies the numer of filled spaces in the array.

The test for this method is:

@Test
public void testInitialsArray()
{
    WaitingList w1 = new WaitingList();
    assertEquals(null,w1.initialsArray());
    w1.addName("Bushell, Greg");
    w1.addName("Kent, Clark");
    w1.addName("Crunch, Captain");
    w1.addName("Fields, Justin");
    w1.addName("Kent, Clark");
    w1.addName("Wayne, Bruce");
    w1.addName("Jordan, Michael");
    String[] actualInitials = w1.initialsArray();
    String[] expectedArrays = {"GB","CK","CC","JF","CK","BW","MJ"};
    for(int i = 0; i < actualInitials.length; i  )
    {
        assertEquals(expectedArrays[i],actualInitials[i]);
    }

}

My problem is line 2 of the test, everything else works except for this, to be honest I am not sure what this is even ment to be testing.

Thanks for the help.

I have not tried anything yet seeing as though I don't even know what is being tested in line 2.

CodePudding user response:

since you initialized your array in the initialsArray method your array will not be null. If you are testing for an empty array, you should just check to see if the arrays length is equal to 0.

CodePudding user response:

The initialsArray() method defines and returns an array.

public String[] initialsArray() {
  String[] initials = new String[numberActive];
  ... fill array ...
  }
  return initials;
}

So the method will never return null which means your assertion will always fail.

assertEquals(null , w1.initialsArray());

p.s. assuming this is a JUnit test, you should be using assertNull(w1.initialsArray());

  • Related