Jack Parkinson Jack Parkinson - 8 months ago 32
Java Question

how to test a method of swapping 2 elements in array using Junit

I have write 2 method in class which swaps 2 elements in array. But I am not sure how to test my methods in JUnit, I want to test if the 2 elements as correctly swapped, and to check if the index in array is valid. Finally a test to check if method will swap strings as well as double.

import java.util.Arrays;

public class GenericExample {

int index1;
int index2;

public static <T> T [] swap(T[] array, int index1, int index2)
T temp = array[index1];
array [index1] = array [index2] ;
array [index2] = temp;

return array;


public static void main(String[] args) {
Integer [ ] array = {1, 2, 3, 4};
System.out.println("Array is: " + Arrays.toString(array));
System.out.println("Array is: " + Arrays.toString(array));


This is the test class which I have created to test the code of this.


Very simple:

public testSwappingFirstAndSecondElement() {
  String input[] = { "1", "2"};
  String expectedOutput[] = { "2", "1"};

  assserThat(swap(input, 0, 1), is(expectedOutput));

is about all you need. Meaning: you create some "known" input; you create "known output" for a specific swap operation; and then you invoke your swap method and check if the returned array matches your expectation.

The real work here: determining all the testcases you have to write, corner conditions and such. For example you would also have tests that call swap(null, -1, -2) ... just to be sure that all such invalid inputs result in that result that you define should come out ...