Junit测试堆栈弹出

时间:2014-05-05 06:28:07

标签: java junit stack

我正在尝试使用Junit测试我的堆栈是否正常工作。我得到了输出:

testPopEmptyStack(StackTesting.TestJunitStack): null
false

但是我希望得到一个输出true,因为在我的堆栈类中。如果pop()堆叠中没有nodes,我希望它为throw new EmptyStackException()

堆栈类:

public class Stack {
    Node top;
    int count = 0;
    ArrayList<Node> stack = new ArrayList<Node>();

    public boolean checkEmpty() {
        if (count == 0) {
            return false;
        }
        else {
            return true;
        }
    }

    public Node getTop() {
        if (count > 0) {
            return top;
        }
        else {
            return null;
        }
    }

    public void pop() {
        if (count > 0) {
            stack.remove(0);
            count--;
        }
        else {
            throw new EmptyStackException();
        }
    }

    public void push(int data) {
        Node node = new Node(data);
        stack.add(node);
        count++;
    }

    public int size() {
        return count;
    }

}

TestJunitStack.java:

public class TestJunitStack extends TestCase{

    static Stack emptystack = new Stack();

    @Test(expected = EmptyStackException.class)
    public void testPopEmptyStack() {
        emptystack.pop();
    }
}

TestRunnerStack.java:

public class TestRunnerStack {
    public void main(String[] args) {
        Result result = JUnitCore.runClasses(TestJunitStack.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
    }
}

修改

static已从testPopEmptyStack

中删除

1 个答案:

答案 0 :(得分:2)

从此处删除static

public static void testPopEmptyStack() {
...