Reputation: 219
For one of my exercises, I have to test my work with JUnit. The first test passed with no errors but the other two have no errors but have failures instead. What does this mean?
public class TestExercise2 {
int [][] numArray = {{3, -1, 4, 0},{5, 9, -2, 6},{5, 3, 7, -8}};
@Test
public void sumOfRows() {
assertEquals(31, Exercise2.sum(numArray));
}
@Test
public void rowsSums() {
int [] i = new int [] {6, 18, 7};
assertArrayEquals(i, Exercise2.rowsSums(numArray));
}
@Test
public void columnSums() {
int [] i = new int [] {13,11,9,-2};
assertArrayEquals(i, Exercise2.columnSums(numArray));
}
Upvotes: 1
Views: 68
Reputation: 661
Your assertions are totally fine and legal, you just need to make sure you're comparing two comparable arrays. I believe the problem is in retrieving wrongly created arrays from Exercise2
's methods rowsSums()
and columnSums()
. So I attempted to create those and couple of helping methods such as getRows()
and getColumns()
.
Now all tests will pass!
public class Exercise2 {
public static int getRows(int[][] numArray) {
// if there are no rows, method will simply return 0
return numArray.length;
}
public static int getColumns(int[][] numArray) {
// if there are no rows,
// ArrayIndexOutOfBoundsException will be thrown
// so need to check
if (getRows(numArray) != 0)
return numArray[0].length;
return 0;
}
public static int[] rowsSums(int[][] numArray) {
// getRows(numArray) will return 3
int[] rowsSums = new int[getRows(numArray)];
int sum = 0;
// iterating over an array
for (int i = 0; i < getRows(numArray); i++) {
for (int j = 0; j < getColumns(numArray); j++) {
sum += numArray[i][j];
}
// when row is finished,
// store sum as [i] element of an array
rowsSums[i] = sum;
// setting sum to zero before iterating over next row
sum = 0;
}
return rowsSums;
}
public static int[] columnSums(int[][] numArray) {
// getColumns(numArray) will return 4
int[] columnSums = new int[getColumns(numArray)];
int sum = 0;
// now we iterate over columns first
// so i < getColumns()
for (int i = 0; i < getColumns(numArray); i++) {
for (int j = 0; j < getRows(numArray); j++) {
// swapped i and j
sum += numArray[j][i];
}
// same thing as before
columnSums[i] = sum;
sum = 0;
}
return columnSums;
}
}
You can also add a sizesOfArray()
test to verify correctness of calculations.
@Test
public void sizesOfArray() {
assertEquals(3, Exercise2.getRows(numArray));
assertEquals(4, Exercise2.getColumns(numArray));
// ArrayIndexOutOfBoundsException will not be thrown
assertEquals(0, Exercise2.getRows(new int[0][0]));
assertEquals(0, Exercise2.getColumns(new int[0][0]));
}
Upvotes: 1
Reputation: 608
This means that the method the methods being tested in other two test cases are not returning the result as per your expectation and assertArrayEquals
method checks your expectation for you. Refer to the documentation for more information.
Upvotes: 4