IDEA出现import org.junit.Test飘红解决方案
問題描述:
import org.junit.Test;飄紅
問題分析:
Spring Boot新版本默認使用Junit5,pom依賴如下圖,此時不能直接使用import org.junit.Test
如果項目中要使用舊版的Junit4,那么在pom文件中要刪除掉<exclusions>這個對舊版本的支持,同時導入Junit4的相關依賴,如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope> </dependency> <dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope> </dependency>(以上starter和junit中的<scope>test</scope>都需要刪除,下文會說明原因,復制時請注意)
修改完依賴之后還是會報錯
此時需要打開file-project structure,把Maven: junit:junit:4.12后面的test改成compile,然后點擊apply再點擊ok。如下圖所示
然后我們發現Test飄紅消失了。
但是新的問題出現了,當輸入完import org.junit.Test;之后立馬消失,如下圖
參考別人的博客:解決方法是刪掉pom.xml文件中junit依賴的scope這一行,這一行的意思是:范圍只能在test目錄下使用,在其他包下使用時不能導入。刪掉改行即可。
但是并沒有成功,還是會消失。
繼續找bug
原來是auto import里面有兩個方框不要框選!
大功告成可以測試
具體測試代碼
package com.example.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @SpringBootTest @RunWith(SpringRunner.class)public class GetPersonInfoController {//獲取配置文件中的age@Value("${age}")private int age;//獲取配置文件中的name@Value("${name}")private String name;//該注解表示一個測試方法@Testpublic void getAge(){System.out.println(age);}//該注解表示一個測試方法@Testpublic void getName(){System.out.println(name);} }參考博客
Spring Boot中進行Junit測試
import org.junit.Test后立馬消失的問題
總結
以上是生活随笔為你收集整理的IDEA出现import org.junit.Test飘红解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 现役武警考军校要多少分
- 下一篇: 演示如何使用application.ym