【问题标题】:Bean autowired as null for integration test using spring boot 2.1.15.RELEASE(junit 4)使用 Spring Boot 2.1.15.RELEASE(junit 4) 进行集成测试的 Bean 自动装配为 null
【发布时间】:2022-01-07 03:24:09
【问题描述】:

以下是导致问题的我的代码,它使用 spring-boot-starter-parent 2.1.15.RELEASE(此版本中有 junit 4)。在这种情况下,总结,标题所有 bean 都被注入为 null .

import com.example.demo.helpers.Subtitle;
import com.example.demo.helpers.Summary;
import com.example.demo.helpers.Title;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;

@SpringBootTest(classes = {Summary.class, Title.class, Subtitle.class},webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = org.springframework.boot.test.context.ConfigFileApplicationContextInitializer.class)
public class DemoApplicationTests {

    @Autowired
    ApplicationContext context;  // null

    @Autowired
    Summary summary;    // null

    @Autowired
    Title title;        // null

    @Test
    public void contextLoads() {
        System.out.println("executed testcase..");
    }
}

但是,当我将 spring-boot-starter-parent 的版本升级到 2.6.1(其中包含 junit 5)时。所有自动装配的 bean 都被正确注入。

但是有一定的限制,我目前无法升级版本。

【问题讨论】:

    标签: java spring spring-boot integration-testing


    【解决方案1】:

    你不见了

    @RunWith(SpringRunner.class)
    

    否则自动装配在 JUnit 4 上不起作用

    SpringRunner vs SpringBootTest

    【讨论】:

    • 感谢 Johannes.Post 添加上面的注释,所有的 bean 都自动装配了。
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2018-07-19
    • 2016-10-10
    • 2020-02-09
    • 2021-07-17
    • 2014-03-11
    • 2018-02-15
    • 2018-02-01
    相关资源
    最近更新 更多