Implementing the API class

Having done all this, the last thing we will need is to have QuickSort as a simple class (all the real work was already done in different classes).

public class QuickSort<E> implements Sort<E> { 
public void sort(SortableCollection<E> sortable) {
int n = sortable.size();
Qsort<E> qsort = new Qsort<>(comparator,swapper);
qsort.qsort(sortable, 0, n-1);
}
// ... setter injectors were deleted from the print
}

Do not forget that we also need a test! But, in this case, that is not much different than that of BubbleSort.

@Test 
public void canSortStrings() {
final String[] actualNames = new String[]{
"Johnson", "Wilson",
"Wilkinson", "Abraham", "Dagobert"
};
final String[] expected = new String[]{"Abraham", "Dagobert", "Johnson", "Wilkinson", "Wilson"};
Sort<String> sort = new QuickSort<>();
sort.setComparator(String::compareTo);
sort.setSwapper(new ArraySwapper<String>(actualNames));
sort.sort(new ArrayWrapper<>(actualNames));
Assert.assertArrayEquals(expected, actualNames);
}

This time, we used String array instead of ArrayList. This makes this test simpler and, this time, we already have the support classes.

You may recognize that this is not a unit test. In the case of BubbleSort, the algorithm was implemented in a single class. Testing that single class is a unit test. In the case of QuickSort, we separated the functionality into separate classes, and even into separate packages. A real unit test of the QuickSort class will disclose the dependency of that class on other classes. When this test runs, it involves the execution of Partitioner and also Qsort; therefore, it is not really a unit test.

Should we bother about that? Not really. We want to create unit tests that involve a single unit to know where the problem is when a unit test fails. If there were only integration tests, a failing test case would not help a lot in pointing out where the problem is. All it says is that there is some problem in the classes that are involved in the test. In this case, there are only a limited number of classes (three) that are involved in this test and they are tied together. They are actually tied together and related to each other so closely that in the real production code, I would have implemented them in a single class. I separated them here to demonstrate how to test a single unit and also to demonstrate Java 9 module support that needs a bit more than a single class in a JAR file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.157.197