Solution Review: Test a Stack
Review the solution for the “Test a Stack” exercise.
We'll cover the following...
Solution
Press + to interact
package io.educative.junit5;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertThrows;import java.util.EmptyStackException;import java.util.Stack;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;@DisplayName("Stack")public class StackTest {Stack<Integer> stack;@Nested@DisplayName("When empty")class WhenEmpty {@BeforeEachvoid createNewStack() {stack = new Stack<>();}@Test@DisplayName("can push values when stack is empty")void canPush() {assertNotNull(stack.push(1));assertNotNull(stack.push(2));}@Test@DisplayName("cannot pop values")void cannotPop() {assertThrows(EmptyStackException.class, () -> stack.pop());}}@Nested@DisplayName("When not empty")class WhenNotEmpty {@BeforeEachvoid createNewStack() {stack = new Stack<>();stack.push(1);stack.push(2);}@Test@DisplayName("can push values when stack is not empty")void canPush() {assertNotNull(stack.push(3));assertNotNull(stack.push(4));}@Test@DisplayName("can pop values")void canPop() {assertNotNull(stack.pop());}@Test@DisplayName("pop values until empty")void popUntilEmpty() {assertNotNull(stack.pop());assertNotNull(stack.pop());assertThrows(EmptyStackException.class, () -> stack.pop());}}}
Explanation
- First, add all required libraries.
- Create an
integer
stack in line 16. - Create two nested