簡體   English   中英

Bean 自動裝配為 null 用於使用 spring 引導 2.1.15.RELEASE(junit 4)進行集成測試

[英]Bean autowired as null for integration test using spring boot 2.1.15.RELEASE(junit 4)

以下是導致問題的我的代碼,它使用 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 都被正確注入。

但是有一定的限制,我現在無法升級版本。

你不見了

@RunWith(SpringRunner.class)

否則自動接線在 JUnit 4 上不起作用

SpringRunner 與 SpringBootTest

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM