用JUNIT测试堆栈的例子
时间: 2023-12-08 10:00:03 浏览: 21
以下是一个使用JUnit测试堆栈的示例:
```
import static org.junit.Assert.*;
import java.util.EmptyStackException;
import org.junit.Before;
import org.junit.Test;
public class StackTest {
private Stack stack;
@Before
public void setUp() {
stack = new Stack();
}
@Test
public void testPush() {
stack.push(1);
assertEquals(1, stack.size());
}
@Test
public void testPop() {
stack.push(1);
stack.push(2);
int result = stack.pop();
assertEquals(2, result);
assertEquals(1, stack.size());
}
@Test(expected = EmptyStackException.class)
public void testPopEmptyStack() {
stack.pop();
}
@Test
public void testPeek() {
stack.push(1);
stack.push(2);
int result = stack.peek();
assertEquals(2, result);
assertEquals(2, stack.size());
}
@Test(expected = EmptyStackException.class)
public void testPeekEmptyStack() {
stack.peek();
}
@Test
public void testIsEmpty() {
assertTrue(stack.isEmpty());
stack.push(1);
assertFalse(stack.isEmpty());
}
@Test
public void testSize() {
assertEquals(0, stack.size());
stack.push(1);
assertEquals(1, stack.size());
}
}
```
在这个例子中,测试类StackTest包含了几个测试方法来确保堆栈的正确性。在@Before注释的setUp方法中,我们创建了一个新的堆栈来测试。在testPush方法中,我们将整数1推入堆栈,并使用assertEquals方法来检查堆栈的大小是否为1。在testPop方法中,我们先将整数1和2推入堆栈,然后弹出堆栈的顶部元素,并使用assertEquals方法来检查弹出的值是否为2,堆栈的大小是否为1。在testPopEmptyStack和testPeekEmptyStack方法中,我们测试当堆栈为空时是否会抛出EmptyStackException异常。在testIsEmpty方法中,我们测试当堆栈为空时,isEmpty方法是否返回true,当堆栈不为空时,是否返回false。在testSize方法中,我们测试堆栈的大小是否正确。