Binary Search In Java Test

Here are some test cases for BinarySearchInJava. In order to pass the search must be capable of determining whether a value is in the array, returning an index to the value if it is, and throwing an exception when asked to return an index to a value that is not in the array. I am interested in what XP might consider to be a proper set of tests for this. -- PhilGoodwin

 public class BinarySearchTest extends TestCase
 {
    int[] anArray = {1,2,3,4,6,7,8};

BinarySearchTest( String name ) { super( name ); }

protected void setUp(){}

public static Test suite() { TestSuite suite= new TestSuite(); suite.addTest( new BinarySearchTest("in array") { protected void runTest() { this.testIsInArray(); } }); suite.addTest( new BinarySearchTest("not in array") { protected void runTest() { this.testNotInArray(); } }); suite.addTest( new BinarySearchTest("throws") { protected void runTest() { this.testThrows(); } }); suite.addTest( new BinarySearchTest("doesn't throw") { protected void runTest() { this.testThrowsNot(); } }); return suite; }

public void testNotInArray() { BinarySearch failSearch = new BinarySearch( 5, anArray ); assert( failSearch.targetIsInArray() == false ); }

public void testIsInArray() { BinarySearch successSearch = new BinarySearch( 2, anArray ); if( successSearch.targetIsInArray() ) { assert( "Target was not found in proper location", anArray[ successSearch.indexOfTarget() ] == 2 ); } else { fail( "Target wasn't found" ); } }

public void testThrows() { try { BinarySearch.findIndexOf( 5, anArray ); fail("Exception not thrown"); } catch(Exception e){} }

public void testThrowsNot() { try { BinarySearch.findIndexOf( 4, anArray ); } catch(Exception e) { fail("Exception thrown"); } } }


CategoryJava

EditText of this page (last edited May 18, 2001) or FindPage with title or text search