Testing
When you are writing programs, it's normal to have errors, and instead of using the autograder, we could write tests for ourselves.
We will write a test method void testSort() first to test a sort() method before we really implement the method.
Ad Hoc Testing
We could easily create a test, such as the code below, which will return nothing or the first mismatch of the provided arrays.
We should not use == while comparing two array objects because this operation will simply compare the memory address pointed by the two variables.
public class TestSort {
/** Tests the sort method of the Sort class. */
public static void testSort() {
String[] input = {"i", "have", "an", "egg"};
String[] expected = {"an", "egg", "have", "i"};
Sort.sort(input);
for (int i = 0; i < input.length; i += 1) {
if (!input[i].equals(expected[i])) {
System.out.println("Mismatch in position " + i + ", expected: " + expected + ", but got: " + input[i] + ".");
break;
}
}
}
public static void main(String[] args) {
testSort();
}
}JUnit
With the JUnit library, our test method could be simplified to the following codes:
Selection Sort
Basic steps of selection sort:
Find the smallest item.
Move it to the front.
Selection sort the remaining N-1 items (without touching the front item).
findSmallest()
Since < can't compare strings, we could use the compareTo method.
Test the method above:
Swap
Recursive Array Helper Method
Since Java doesn't support array slicing (x[1:2]), we should add a helper method to recursively sort the whole array.
However, the findSmallest method doesn't work well since it will start from 0 instead of the start point. We could easily fix it.
Enhanced JUnit Test
To allow IntelliJ to automatically run the tests, we could modify our test structure as the following rules:
Import the library
org.junit.Test.Precede each method with
@Test(no semi-colon).Change each test method to be non-static.
Remove our main method from the
TestSortclass.
Last updated