SpringUnit Tutorial

ClassUnder Test 2: Range

Previous Next
The next examples use a different class under test. Range is a bean that contains two properties, upper and lower. Because this is for demonstration purposes only, it is not a complete implementation of a range abstraction. However, there are two aspects to this class that make it very interesting for testing. First, it has a method, isWithin, that takes an item as an argument and returns true or false, depending upon whether the argument was below, between (inclusive), or above the end points of the range. Because this presents interesting boundary conditions, it makes for a good test demonstration. The second interesting feature of this class is that it is generic: the types of the upper and lower bounds can be any type, provided that they are Comparable. (The fact that these types are Comparable is essential to the implementation of the isWithin method.) Here is the Range class, abbreviated.
package org.springunit.examples;

public class Range<T extends Comparable<T>> {
	
	/**
	 * Create range with <code>upper</code>
	 * and <code>lower</code> bounds.<br/>
	 * @param upper Upper bound of range
	 * @param lower Lower bound of range
	 */
	public Range(T upper, T lower) {
		setUpper(upper);
		setLower(lower);
	}
	
	/**
	 * Is item between upper and lower
	 * bounds?
	 */
	public boolean isWithin(T item) {
		return item.compareTo(this.lower) >= 0 && item.compareTo(this.upper) <= 0;
	}
	
	/**
	 * Lower bound of range.<br/>
	 * @param lower New lower bound
	 */
	public void setLower(T lower) {
		this.lower = lower;
	}
	
	/**
	 * Upper bound of range.<br/>
	 * @param upper New upper bound
	 */
	public void setUpper(T upper) {
		this.upper = upper;
	}
	
	private T lower;
	private T upper;
	
}
The fact that the Range class accepts generic parameters means that the same algorithm can be applied to different data types. It's a good idea to test such a class with different data types. In Example 4, we will create a test of the Range class where the upper and lower bounds are of type org.springunit.examples.CompositeDateTime. in Example 5, we will create a second test of the Range class where the bounds are instances of java.util.GregorianCalendar. We will limit our testing to the isWithin method. There are five cases that we should cover:
  1. the item is below the lower bound
  2. the item is equal to the lower bound
  3. the item is between but not equal to the bounds
  4. the item is equal to the upper bound
  5. the item is above the upper bound
Previous Next