...
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
class ArrayUtils { // Version 3 for find_highest_in_array_of_any_number() public int findHighest(int array[]) { int highestSoFar = Integer.MIN_VALUE; // it could be argued that it should be array[0], to restrict numbers to within that which is passed in for (int i = 0; i < array.length; i++) { if (array[i] > highestSoFar) highestSoFar = array[i]; } return highestSoFar; } } |
Final Version - handles exceptions
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public class ArrayUtilsTest
{
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void find_highest_in_empty_array() throws EmptyArrayException
{
// Arrange
int array[] = {};
ArrayUtils arrayUtils = new ArrayUtils();
exception.expect(EmptyArrayException.class);
// Act
int result = arrayUtils.findHighest(array);
}
@Test
public void find_highest_in_array_of_one() throws EmptyArrayException
{
// Arrange
int array[] =
{
10
};
ArrayUtils arrayUtils = new ArrayUtils();
// Act
int result = arrayUtils.findHighest(array);
// Assert
assertThat(result, is(10));
}
@Test
public void find_highest_in_array_of_two_pre_ordered() throws EmptyArrayException
{
// Arrange
int array[] =
{
20, 10
};
ArrayUtils arrayUtils = new ArrayUtils();
int expectedResult = 20;
//Act
int result = arrayUtils.findHighest(array);
// Assert
assertThat(result, is(expectedResult));
}
@Test
public void find_highest_in_array_of_two_ascending() throws EmptyArrayException
{
// Arrange
int array[] =
{
10, 20
};
ArrayUtils arrayUtils = new ArrayUtils();
int expectedResult = 20;
//Act
int result = arrayUtils.findHighest(array);
// Assert
assertThat(result, is(expectedResult));
}
@Test
public void find_highest_in_array_of_any_number() throws EmptyArrayException
{
// Arrange
int array[] =
{
10, 5, 30
};
ArrayUtils arrayUtils = new ArrayUtils();
int expectedResult = 30;
//Act
int result = arrayUtils.findHighest(array);
// Assert
assertThat(result, is(expectedResult));
}
} |
CUT
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
class ArrayUtils
{
// Version 2 for find_highest_in_array_of_any_number()
public int findHighest(int array[]) throws EmptyArrayException
{
if( array.length < 1 )
throw new EmptyArrayException("Array is empty");
int highestSoFar = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++)
{
if (array[i] > highestSoFar)
highestSoFar = array[i];
}
return highestSoFar;
}
} |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
package com.celestial.tdd.demo.complete;
/**
*
* @author Selvyn
*/
public class EmptyArrayException extends Exception
{
public EmptyArrayException( String msg )
{
super( msg );
}
} |