2.3. Unit Testing
Robustness tests.
Auxiliary Method
Let us create PriorityQueueTest
and define testRobustnessAux()
that checks the robustness of any PQ inheriting AbstractPriorityQueue
:
L6
: the generic typeT
is defined specifically for this method such that the priority queuepq
, the listkeys
, and the comparatorcomp
take the same typeT
that is comparable.L9
: iterates each of the sorted keys and compares it to the returned value ofpq.remove()
.
What are the advantages of defining a method-level generic type?
Functional Programming
The following code shows a traditional way of iterating over a list (that is equivalent to L7
above):
Java 5 introduced an enhanced for loop that simplified the traditional for loop:
Java 8 introduced lambda expressions that enabled functional programming in Java. The following code takes each key
(as a variable) in keys
and applies it to pq.add()
:
The syntax of the above code can be simplified as follows (as shown in L7
):
What are the main differences between object-oriented programming and functional programming?
Since Java 8, higher-order methods can be defined by parameterizing types of interfaces in the function package.
Test: Robustness
Let us define the testRobustness()
method that calls the auxiliary method testRobustnessAux()
:
L7-9
: tests different types of max-PQs. The keys need to be sorted in reverse order for it to test theremove()
method.L11-13
: tests different types of min-PQs. The keys need to be sorted in the natural order for it to test theremove()
method.
The generic types of the PQs in
L4-5
are explicitly coded as<Integer>
, whereas they are simplified to<>
inL7-13
. When do generic types need to be explicitly coded?
The testRobustness()
method illustrates the benefit of defining AbstractPriorityQueue
such that any type of PQ can be passed to testRobustnessAux()
for unit-testing.
Last updated