有時在使用idea通過Spring Initailizr創建項目時,默認只能創建最近的版本的SpringBoot項目。
這是如果想要換成版本,就可以在項目創建好了之后,在pom文件中直接將版本修改過來。
如下所示
比如在創建項目時默認的版本為2.2.2版本:
<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的低版本:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
這時可能會遇到一個問題,那就是——在高版本時,默認的測試類是沒問題可以使用的
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類
此時可以做如下修改
1、刪除高版本默認導入的org.junit.jupiter.api.Test類,重新導入org.junit.Test類
2、在類上添加注釋@RunWith(SpringRunner.class),如下圖:
注:
- 通過@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);使用前者,名字簡短而已
3、將測試類和測試方法都修改為public
4、最后修改的測試類如下所示:
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"); } }
運行結果: