2014-05-05 153 views
1

我想使用Junit它测试如果我的堆栈工作正常。我得到的输出: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()); 
    } 
} 

EDIT

statictestPopEmptyStack删除

回答

2

从这里

public static void testPopEmptyStack() { 
... 
+0

删除static输出是一样的= [ – Liondancer

+1

试试我的简单测试@Test(预期= EmptyStackException.class) 公共无效testPopEmptyStack(){ 抛出新的EmptyStackException(); } –

+0

嗯奇怪,它有相同的输出。我喜欢这个测试案例 – Liondancer