使用@SpringBootTest注解進行單元測試
概述
@SpringBootTest注解是SpringBoot自1.4.0版本開始引入的一個用于測試的注解。基本用法如下:
1. 添加Maven依賴
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
2. 編寫啟動入口類
@SpringBootApplication public class StartUpApplication { public static void main(String[] args) { SpringApplication.run(StartUpApplication.class, args); } }
3. 編寫Controller類
@RestController public class HelloController { @RequestMapping("/") public String index() { return "Hello Spring Boot,Index!"; } @RequestMapping(value = "/test", method = RequestMethod.GET) public String test() { return "Spring Boot Test Demo!"; } }
4. 編寫測試類
@RunWith(SpringRunner.class) @SpringBootTest(classes = StartUpApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloControllerTest { /** * @LocalServerPort 提供了 @Value("${local.server.port}") 的代替 */ @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate restTemplate; @Before public void setUp() throws Exception { String url = String.format("http://localhost:%d/", port); System.out.println(String.format("port is : [%d]", port)); this.base = new URL(url); } /** * 向"/test"地址發(fā)送請求,并打印返回結(jié)果 * @throws Exception */ @Test public void test1() throws Exception { ResponseEntity<String> response = this.restTemplate.getForEntity( this.base.toString() + "/test", String.class, ""); System.out.println(String.format("測試結(jié)果為:%s", response.getBody())); }
其中,classes屬性指定啟動類,SpringBootTest.WebEnvironment.RANDOM_PORT經(jīng)常和測試類中@LocalServerPort一起在注入屬性時使用。會隨機生成一個端口號。
總結(jié)
我們發(fā)現(xiàn),隨著Spring boot 版本的提升,單元測試變得更簡單了。
到此這篇關(guān)于使用@SpringBootTest注解進行單元測試的文章就介紹到這了,更多相關(guān)@SpringBootTest 單元測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
@CacheEvict中的allEntries與beforeInvocation的區(qū)別說明
這篇文章主要介紹了@CacheEvict中的allEntries與beforeInvocation的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12spring 中事務(wù)注解@Transactional與trycatch的使用
這篇文章主要介紹了spring 中事務(wù)注解@Transactional與trycatch的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06java編程中拷貝數(shù)組的方式及相關(guān)問題分析
這篇文章主要介紹了java編程中拷貝數(shù)組的方式及相關(guān)問題分析,分享了Java中數(shù)組復(fù)制的四種方式,其次對二維數(shù)組的簡單使用有一段代碼示例,具有一定參考價值,需要的朋友可以了解下。2017-11-11Java鏈表的天然遞歸結(jié)構(gòu)性質(zhì)圖文與實例分析
這篇文章主要介紹了Java鏈表的天然遞歸結(jié)構(gòu)性質(zhì),結(jié)合圖文與實例形式分析了java鏈表中遞歸操作的原理、實現(xiàn)技巧與相關(guān)注意事項,需要的朋友可以參考下2020-03-03