java - JUnit: test builder with private field -


i'm beginner , have problem junit test in constructor of class.

the class want test called intsortedarray , 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 - can't create array of negative length.");         }         else {             elements = new int[initialcapacity];             size = 0;         }     }      public intsortedarray(int[] a) {         elements = new int[a.length + 16];         for(int = 0; < a.length; i++)             elements[i] = a[i];         size = a.length;         insertionsort(elements);     }      //other code...  } 

with eclipse created class 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 write test class intention test methods of class intsortedarray, including constructors.

the first method testconstructorarray16elements() wants test first builder. thought check if creation of array elements done properly, loop counts how long elements , make sure along 16 (as required).

but eclipse generates (rightly) mistake because elements private. how can fix error? don't want put public field , if possible avoid creating method public int[] getelements().

what recommend?

another question: can 2 assert same method? 1 test length of array , other test size 0.

i hope not have made big mistakes, first time use junit.

ps: how can test second constructor?

thank much!

it looks class fields declare private trying access outside class. need provide accessors methods in class make them visible:

private int[] elements; private int size;  public static final int max = 16;  public int[] getelements() { ... } public int getsize() { return size; } 

then able write below code:

isa = new intsortedarray(); int expected = 0; for(int i: isa.getelements()) {   expected += 1; } assertequals(expected, intsortedarray.max ); 

it looks constructor has created array 16 integers, not initialize value. should have below code:

public intsortedarray() {     this.elements = new int[max];     this.size = 0;     (int i=0 ; < max ;i++) {        elements[i] = i;        size++;     } } 

Comments

Popular posts from this blog

java - Could not locate OpenAL library -

node.js - How to mock a third-party api calls in the backend -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -