【问题标题】:Are the project beans already instantiated when we try to run a junit test in spring boot当我们尝试在 Spring Boot 中运行 junit 测试时,项目 bean 是否已经实例化
【发布时间】:2020-11-04 18:32:00
【问题描述】:

我是 Spring 和 Spring Boot 的新手。 对于作为休息控制器的 Spring Boot 应用程序,我有一些 bean 以及我的数据源。 我使用我的数据源来创建 jdbc 模板。现在,当我在我的休息控制器代码中时,我拥有所有这些豆子@Autowired,它们工作得很好。

我的问题是关于 junit 测试部分。 当我在 src/test/java 中编写测试代码并在 IDE 中执行我的测试类时,我的 src/main/javacode 中定义的 bean 是否在测试用例执行之前实例化?

【问题讨论】:

    标签: spring-boot junit spring-bean


    【解决方案1】:

    您可以使用同一个容器,或者为了测试目的而实例化另一个容器,为此您将分别提供另一个 Spring 容器的配置:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:test-context.xml")
    public class SomeClassTest{...}
    

    但是,您也可以启用对加载应用程序上下文的支持,然后在您的 JUnit 装置中使用 @Autowired 字段,这也可以正常工作:

    @RunWith(SpringRunner.class)
    public class SomeTestClass {
        ....
        @Autowired
        ApplicationContext context;
        ....
    }
    

    从这里,你可以得到任何你想要的豆子。

    【讨论】:

    • 谢谢乔治。所以默认情况下它们还没有被实例化。通过自动装配 ApplicationContext 我们以后可以使用它们吗?
    • 您可以使用多种方法,但是,请参阅我的更新答案。
    猜你喜欢
    • 2016-10-13
    • 2012-05-04
    • 2019-01-01
    • 2018-07-19
    • 2022-01-19
    • 2019-12-26
    • 1970-01-01
    • 2018-04-06
    • 2018-02-02
    相关资源
    最近更新 更多