在springBoot的内部静态测试类中初始化bean

问题描述

我正在使用嵌套类在 Spring Boot 中编写单元测试用例。我的测试用例文件是:

@RunWith(nestedRunner.class)
@SpringBoottest
@TestInstance
@AutoConfiguremockmvc
public class OuterTestCase {

        public static class InnerTestCases {

             @Autowired
             private RestTemplate restTemplate;
             @Autowired
             private mockmvc mockmvc;

             @Test
             public void testcase(){
              //do Something
             }
        }
}

但是在 testCase 方法中尝试使用 RestTemplate 时,我得到了 NPE。

我无法在内部类中初始化 bean。

解决方法

静态类在类加载的早期阶段被初始化。除非使用静态类初始化 Autowired 类,否则您将遇到上述错误。