JUnit example

A testing example for insertionSort. Open the sorting methods project in Eclipse and add this file:


import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Random;

public class TestInsertionSort {
	
	/**
	 * A test to check that a given 4-element array is sorted
	 */
	@Test
	public void testSimple() {
		Integer [] toSort = {3, 5, 1, 2};
		Integer [] sorted = {1, 2, 3, 5};
		SortingMethods.insertionSort(toSort);
		assertArrayEquals(toSort, sorted);
	}
	
	/**
	 * A test to check if the resulting arrays are sorted
	 */
	@Test
	public void testSorted() {
		for (int i = 0; i < 5; ++i) {
			Integer [] toSort = randomInts(1, 101, 20 * (i + 1));
			SortingMethods.insertionSort(toSort);
			assertTrue(isSorted(toSort));
		}
	}
	
	/**
	 * A test to check if the resulting array is sorted and 
	 * contains the same elements as before
	 */
	@Test
	public void testSameElements() {
		Integer [] toSort = randomInts(1, 101, 50);
		Integer [] elements = new Integer[toSort.length];
		for(int i = 0; i < toSort.length; ++i) {
			elements[i] = toSort[i];
		}
		SortingMethods.insertionSort(toSort);
		assertTrue(isSorted(toSort));
		for (int i = 0; i < elements.length; ++i) {
			boolean found = false;
			for(int j = 0; j < toSort.length; ++j) {
				if (elements[i].equals(toSort[j]))
					found = true;
			}
			assertTrue(found);
		}
	}
	
	private static Integer [] randomInts(int min, int max, int num) {
		if (min >= max || num < 0) {
			throw new IllegalArgumentException();
		}
		Integer [] theInts = new Integer[num];
		Random rand = new Random();
		for (int i = 0; i < num; ++i){
			theInts[i] = rand.nextInt(max - min) + min;			
		}
		return theInts;
	}
	
	private static <T extends Comparable<T>> boolean isSorted(T [] arr) {
		for (int i = 0; i < arr.length - 1; ++i) {
			if (arr[i].compareTo(arr[i+1]) > 0) {
				return false;
			}
		}
		return true;
	}
	
}



If there are compilation errors after you have added the file, go to QuickFix and choose "fix project setup". This should give you an option of importing JUnit package.

When compilation errors disappear, go to "Run as" and choose "JUnit Test".


CSci 2101 course web site.