Overview

Currently, a @TestBean factory method will be found in the directly enclosing class for a @Nested test class; however, such a factory method will not be found in the enclosing class of the enclosing class, etc.

In other words, the search algorithm for a factory method must be recursive when searching enclosing classes for @Nested test classes.

Example

NestedLevel1 passes because the testField1() factory method is found, but NestedLevel2 fails because the testField2() factory method cannot be found.

@SpringJUnitConfig
class MultipleNestingLevels {

    static String testField1() {
        return "one";
    }

    static String testField2() {
        return "two";
    }

    @Nested
    class NestedLevel1 {

        @TestBean(name = "field1", methodName = "testField1")
        String field1;

        @Test
        void test() {
            assertThat(field1).isEqualTo("one");
        }

        @Nested
        class NestedLevel2 {

            @TestBean(name = "field2", methodName = "testField2")
            String field2;

            @Test
            void test() {
                assertThat(field1).isEqualTo("one");
                assertThat(field2).isEqualTo("two");
            }
        }
    }

    @Configuration
    static class Config {
        @Bean
        String field1() {
            return "replace me 1";
        }

        @Bean
        String field2() {
            return "replace me 2";
        }
    }

}