概述
@SpringBootTest注解是SpringBoot自1.4.0版本開始引入的一個用于測試的注解?;居梅ㄈ缦拢?/p>
1. 添加Maven依賴
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
< 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. 編寫啟動入口類
1
2
3
4
5
6
|
@SpringBootApplication public class StartUpApplication { public static void main(String[] args) { SpringApplication.run(StartUpApplication. class , args); } } |
3. 編寫Controller類
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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. 編寫測試類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
@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"地址發送請求,并打印返回結果 * @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( "測試結果為:%s" , response.getBody())); } |
其中,classes屬性指定啟動類,SpringBootTest.WebEnvironment.RANDOM_PORT經常和測試類中@LocalServerPort一起在注入屬性時使用。會隨機生成一個端口號。
總結
我們發現,隨著Spring boot 版本的提升,單元測試變得更簡單了。
到此這篇關于使用@SpringBootTest注解進行單元測試的文章就介紹到這了,更多相關@SpringBootTest 單元測試內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/limenghua9112/article/details/79694849