In: Computer Science
For java.
It's your turn to write a test suite! Let's start out simple. Create a public class TestArraySum that provides a single void class method named test. test accepts a single parameter: an instance of ArraySum.
Each ArraySum provides a method sum that accepts an int[] and returns the sum of the values as an int, or 0 if the array is null. However, some ArraySum implementations are broken! Your job is to identify all of them correctly.
To do this you should use assert to test various inputs. Here's an example:
assert sum.sum(null) == 0;
Your function does not need to return a value. Instead, if the code is correct no assertion should fail, and if it is incorrect one should.
As you design test inputs, here are two conflicting objectives to keep in mind:
The program can be written as
class ArraySum
{
int sum(int[] arr)
{
int sum = 0;
if (arr.length ==0)
return 0;
for (int i = 0; i < arr.length;
i++)
sum+=arr[i];
return sum;
}
}
class TestArraySum
{
void test( ArraySum a)
{
int arr[] = {};
int x =a.sum(arr);
System.out.println(" x= "+x);
}
}
public class Test
{
public static void main(String args[])
{
ArraySum a= new ArraySum();
TestArraySum t1= new TestArraySum();
t1.test(a);
}
}
That will print 0.