我正在嘗試為我的應用程序編寫 junit 測試用例。使用 Junit 5 后,我無法使用 @ContextConfiguration 創建必要的 bean。它沒有拋出任何錯誤。但是在測試類中自動裝配 bean 時,我得到了空值我添加了以下依賴項testImplementation "org.junit.jupiter:junit-jupiter-api:5.3.0"testCompile('org.junit.jupiter:junit-jupiter-params:5.3.0')testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.3.0"和我的代碼@ContextConfiguration(classes = ServiceTestContextConfiguration.class)public class ApplicationConfigTest {@Autowiredprivate ApplicationServiceConfiguration 應用服務配置;@ContextConfigurationpublic class ServiceTestContextConfiguration {@Beanpublic ApplicationServiceConfiguration applicationServiceConfiguration() { return new ApplicationServiceConfiguration();}我正在使用 spring-boot 2。
1 回答

長風秋雁
TA貢獻1757條經驗 獲得超7個贊
可能是我們混合了 junit4 和 junit5 的導入。@Configuration讓我們用( )注釋配置類org.springframework.context.annotation.Configuration;。
在主要單元測試中,讓我們使用以下內容,
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ServiceTestContextConfiguration.class)
而不是@Before,使用@BeforeEach并確保所有導入都來自 junit5(包括斷言)
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
添加回答
舉報
0/150
提交
取消