I'm a beginner and I have a problem with JUnit test in the constructor of a class.
The class that I want to test is called IntSortedArray and is as follows:
public class IntSortedArray {
private int[] elements;
private int size;
public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}
public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}
public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}
//other code...
}
With Eclipse I created a class for JUnit:
public class IntSortedArrayUnitTest {
private IntSortedArray isa;
@Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}
}
I started to write a test class with the intention to test all the methods of the class IntSortedArray
, including constructors.
The first method testConstructorArray16Elements()
wants to test the first builder.
So I thought I would check if the creation of the array elements is done properly, so the for loop counts how long elements
and make sure it along 16 (as required).
But Eclipse generates (rightly) a mistake because elements
is private
.
How can I fix this error? I don't want to put the public
field and if possible I would like to avoid creating a method public int[] getElements()
.
What do you recommend?
Another question: I can do two assert the same method? One to test the length of the array and the other to test that size
is 0.
I hope not to have made big mistakes, this is the first time I use JUnit.
PS: how can I test the second constructor?
Thank you very much!