有時在使用idea經過Spring Initailizr建立項目時,默認只能建立最近的版本的SpringBoot項目。web
這是若是想要換成版本,就能夠在項目建立好了以後,在pom文件中直接將版本修改過來。spring
以下所示api
好比在建立項目時默認的版本爲2.2.2版本:springboot
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
而後咱們修改成1.5.10的低版本:ide
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
這時可能會遇到一個問題,那就是——在高版本時,默認的測試類是沒問題可使用的spring-boot
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringBootTestWebApplicationTests { @Test void contextLoads() { System.out.println("hello world"); } }
可是在更換成低版本以後,測試類將會報錯,以下所示,沒法導入在2.2.2高版本中使用的org.junit.jupiter.api.Test類測試
此時能夠作以下修改idea
一、刪除高版本默認導入的org.junit.jupiter.api.Test類,從新導入org.junit.Test類spa
二、在類上添加註釋@RunWith(SpringRunner.class),以下圖:code
注:
- 經過@RunWith註解,更改測試運行器,更改使用的測試類爲SpringRunner.class,使之適應spring。
- @RunWith(SpringRunner.class)使用了Spring的SpringRunner,以便在測試開始的時候自動建立Spring的應用上下文。其餘的想建立spring容器的話,就得子啊web.xml配置classloder。 註解了@RunWith就能夠直接使用spring容器,直接使用@Test註解,不用啓動spring容器
- SpringRunner 繼承了SpringJUnit4ClassRunner,沒有擴展任何功能(查看源碼能夠看到public final class SpringRunner extends SpringJUnit4ClassRunner);使用前者,名字簡短而已
三、將測試類和測試方法都修改成public
四、最後修改的測試類以下所示:
package com.susu.springboot; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootTestApplicationTests { @Test public void contextLoads() { System.out.println("hello world"); } }
運行結果: