Skip to content
Advertisement

How to write a JUnit test case for ArrayStack methods

I am implementing an ArrayStack and we have to create a tester for it with JUnit and I wasn’t sure what to add to check if these two methods are working. The method addAll appends all values from the given list into the other list. Equals checks if two ArrayStacks are equal. I think I would have to create another stack but I wasn’t sure how to code it to add to the original stack or to check if they equal each other with JUnit. Method checkCapacity is there if it makes it easier to understand my addAll method as it calls it in the method.

public boolean equals (Object other) {
if (other instanceof array) {
return this.size() ==((array) other).size() && 
this.toString().equals(other.toString());
}
return false;
}

public void addAll (array other) {
checkCapacity(size+other.size);
    for (int i=0; i<other.size; i++) {
    add (other.arr[i]);
     }

}

private void checkCapacity(int capacity) {
    if (capacity>arr.length) {
       throw new IllegalStateException ();
     }
}

Advertisement

Answer

you need to design test cases for both these methods. test case includes input (args) and expected result. for example:

  1. addAll null arg -> NullPointerException (or perhaps something else)
  2. addAll with empty array -> unchanged this stack
  3. addAll with array with 1 item -> item is added to this stack
  4. addAll with array with several items -> items are added to this stack. check that order of items in stack is correct
  5. addAll with array with null item -> ?
  6. if your code is supposed to be thread safe, you need to design tests for this as well

regarding how to write the tests using junit, I suggest to start with one case and then expand from there

Advertisement