@DisplayName("嵌套测试")publicclassTestingAStackDemo{Stack<Object> stack;/**
* 外层测试不能访问内层测试的beforeEach
*/@Test@DisplayName("is instantiated with new Stack()")voidisInstantiatedWithNew(){newStack<>();}@Nested@DisplayName("when new")classWhenNew{@BeforeEachvoidcreateNewStack(){
stack =newStack<>();}@Test@DisplayName("is empty")voidisEmpty(){assertTrue(stack.isEmpty());}@Test@DisplayName("throws EmptyStackException when popped")voidthrowsExceptionWhenPopped(){assertThrows(EmptyStackException.class, stack::pop);}@Test@DisplayName("throws EmptyStackException when peeked")voidthrowsExceptionWhenPeeked(){assertThrows(EmptyStackException.class, stack::peek);}@Nested@DisplayName("after pushing an element")classAfterPushing{String anElement ="an element";@BeforeEachvoidpushAnElement(){
stack.push(anElement);}/**
* 内层的test可以驱动外层的beforeEach
*/@Test@DisplayName("it is no longer empty")voidisNotEmpty(){assertFalse(stack.isEmpty());}@Test@DisplayName("returns the element when popped and is empty")voidreturnElementWhenPopped(){assertEquals(anElement, stack.pop());assertTrue(stack.isEmpty());}@Test@DisplayName("returns the element when peeked but remains not empty")voidreturnElementWhenPeeked(){assertEquals(anElement, stack.peek());assertFalse(stack.isEmpty());}}}}