0

I have created a generic swapping algorithm. In order to for this an array is required and the elements are swapped using integer indices.

I have created a JUnit test class for this and cannot figure out what to use instead of assertArrayEquals if the output should be an error.

Here is my attempt:

@Test
public void testNull() {
    GenericMethods gm = new GenericMethods();
    String names[] = null;
    Error err = null;
    //String expectedOutput[] = { "Hugh", "Simon", "Ebrahim", "Diane", "Paula", "Andrew" };
    assertArrayEquals(gm.swap(names, 1, 5), (err));
}

Here is the Generic swap method used

package genericMethods;

import java.util.Arrays;

public class GenericMethods {

    public static <T> T[] swap(T[] names, int index1, int index2) {

        if(names == null){

            return null; //This will return nothing if nothing has been selected
        }


        if ((index1 >= 0 && index1 < names.length) && (index2 >= 0 && index2 < names.length)) {

            T string = names[index1];
            names[index1] = names[index2];
            names[index2] = string; //Will check if a valid name has been selected
        }

        return names;
    }

    public static void main(String[] args) {
        String[] names = new String[] { "Hugh", "Andrew", "Ebrahim", "Diane", "Paula", "Simon" };
        swap(names, 1, 5); //will swap Hugh with Simon 
    }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 1
    Show the implementation of `GenericMethods.swap`. – Andy Turner Jan 16 '17 at 16:52
  • Assuming you mean a throwable error or exception just use a try-catch block. – Thomas Jan 16 '17 at 16:52
  • Also: note that JUnit method parameters are in the order (expected, actual). You should be doing `assertArrayEquals(err, gm.swap(names, 1, 5))`, if you're expecting it to succeed. – Andy Turner Jan 16 '17 at 16:54
  • You don't need to (and shouldn't) create an instance of `GenericMethods` to invoke `swap`. Just invoke `GenericMethods.swap(names, 1, 5)`. – Andy Turner Jan 16 '17 at 16:57
  • Note that your code doesn't throw an exception (or error) if `names` is `null`, as you appear to want to test. It simply returns `null`. – Andy Turner Jan 16 '17 at 17:09

0 Answers0