HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Stack data structure unit testing

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stacktestingstructuredataunit

Problem

I have this contract:

public interface Stack {
    void push(T object);
    T pop();
    int size();
}


I am curious what you think about my test of the size() and pop() in order to prevent bugs (underlying data structure in not being cleaned) in implementation like below:

Implementation:

public class StackImpl implements Stack {
    private int size;
    private Object data[];
    @Override
    public void push(Object object) {
        data[size] = object;
        size++;
    }
    @Override
    public Object pop() {
        --size;
        return data[size];
    }
    @Override
    public int size() {
        return size;
    }
}


Test:

public class StackTest {
    @Test
    public void pushTwoObjectsToEmtyStackCheckThatSizeIsTwo() {
        pushObjectsInOrder(OBJECT_A, OBJECT_B);
        assertEquals(2, stack.size());
    }
    @Test
    public void pushTwoObjectToEmptyStackAndPopTheSameObjectsInReversedOrder() {
        pushObjectsInOrder(OBJECT_A, OBJECT_B);
        assertEquals(OBJECT_B, stack.pop());
        assertEquals(OBJECT_A, stack.pop());
    }
    @Test(expected=IllegalArgumentException.class)
    public void stackDoesntAcceptNullAndThrowExcpetion() {
        stack.push(null);
    }
    @Before
    public void setUp() throws Exception {
        stack = new StackImpl();
    }
    private void pushObjectsInOrder(Object... objects) {
        for (Object object : objects) {
            stack.push(object);
        }
    }
    private static final Object OBJECT_A = new Object();
    private static final Object OBJECT_B = new Object();
    private Stack stack;
}


I'd like to not focus too much on the implementation itself, like whether it should be List or array etc. Assume that you defined interface and going to give to implement it to other guy. Since you defined the contract you are the one who writes a unit test.

Solution

Here are some tests I'd perform at the very least. There may be more you'd want:

  • Create an empty Stack. Test that its size is 0.



  • Push an element onto the stack. Test that its size is now 1.



  • Push another element onto the stack. Test that its size is now 2.



  • Pop an element from the stack. Test that it matches the 2nd pushed value. Check that the size of the stack is now 1.



  • Pop an element from the stack. Test that it matches the 1st pushed value. Check that the size of the stack is 0.



  • Attempt to pop an element from the stack. You should receive an ArrayIndexOutOfBounds exception.

Context

StackExchange Code Review Q#78221, answer score: 6

Revisions (0)

No revisions yet.