Search code examples
javanew-operatorjunit5

Which variable is the result of new operator assigned to in `void isInstantiatedWithNew() {new Stack<>();}`? *(from a JUnit 5 User Guide example)*


The JUnit 5 User Guide contains an example in the Nested Tests section: Particularly, it contains the following code:

@DisplayName("A stack")
class TestingAStackDemo {

    Stack<Object> stack;

    @Test
    @DisplayName("is instantiated with new Stack()")
    void isInstantiatedWithNew() {
        new Stack<>();
    }

    @Nested
    @DisplayName("when new")
    class WhenNew { 

        @BeforeEach
        void createNewStack() {
            stack = new Stack<>();
        }

        @Test
        @DisplayName("is empty")
        void isEmpty() {
            assertTrue(stack.isEmpty());
        }...

I wonder, which variable is the result of the new operator new Stack<>() is assigned to in method void isInstantiatedWithNew()?


Solution

  • The two reasonable explanations for that code are:

    It's a typo, and it was meant to be stack = new Stack<>();, but this isn't a very plausible explanation.

    The more reasonable one is that it tests that the no-arg constructor doesn't throw exceptions. It suits the functionality of the test, and even the name sort of suggests it.

    The nested WhenNew depends on being able to create a new Stack<>() in @BeforeEach, so this verifies that the dependency is met before the nested tests are attempted.