A Junit test class is used to test the class LibraryCounter. Reflection was used to test the private methods. This made the code much more complicated.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
import static org.junit.Assert.*;
public class LibraryCounterTest {
public LibraryCounterTest() { }
@Test
public void medianEasyTest() {
System.out.println("median");
int[] sample = {7,8,9};
Class[] args = new Class[3];
args[0] = int[].class;
args[1] = Integer.TYPE;
args[2] = Integer.TYPE;
try {
Method m = LibraryCounter.class.getDeclaredMethod("median", args);
m.setAccessible(true);
try {
Object o = m.invoke(null, sample, 0, sample.length-1);
int result = (int)o;
assertEquals(8, result);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(LibraryCounterTest.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchMethodException | SecurityException ex) {
Logger.getLogger(LibraryCounterTest.class.getName()).log(Level.SEVERE, null, ex);
}
assertEquals(7, sample[0]);
assertEquals(8, sample[1]);
assertEquals(9, sample[2]);
}
}
This is just the first and simplest test. The method being tested has the following signature private static int median(int[], int, int)
If the method was public
then everything inside the outermost try
could be condensed to one line.
Here is the method being tested from the LibraryCounter class:
/*
*Sorts first, center and last element, swaps the new center element with the one before the new last and returns its value.
*/
private static int median(int[] sample, int start, int end) {
if(sample.length < 3) {
throw new IllegalArgumentException("arrays of length three or greater");
}
int center = start + ((end-start)/2);
if(sample[start] > sample[end])
swap(sample, start, end);
if(sample[start] > sample[center])
swap(sample, start, center);
if(sample[center] > sample[end])
swap(sample, center, end);
int secondLast = end - 1
swap(sample, center, secondLast );
return sample[secondLast];
}
//swaps two elements in array given their positions
private static void swap(int[] sample, int x, int y) {
int temp = sample[x];
sample[x] = sample[y];
sample[y] = temp;
}