【问题标题】:Initialize beans in inner Static test class in springBoot在Spring Boot的内部静态测试类中初始化bean
【发布时间】:2021-03-29 22:46:32
【问题描述】:

我正在使用嵌套类在 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 not working in inner class
  • 基本上必须将内部静态类注释为某种 bean - 也许是@Component。否则你必须自己管理依赖。
  • 添加组件 bean 也不起作用。 @RandyCasburn 我也检查了上面的链接,但这也没有回答我的问题。

标签: java spring-boot junit junit-runner


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2011-02-26
    • 2016-08-08
    • 2019-05-30
    • 2017-05-10
    • 2011-01-19
    • 2015-09-27
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多