Spring Bootå®ç°æµè¯åæå é¨ç½²
Spring Bootéé¢æ常ç¨çæ¯åå æµè¯äºï¼Junitåå æµè¯ãSpring Bootä¹æä¾å¯¹åå æµè¯çéæï¼é¤æ¤ä¹å¤ï¼è¿æä¾äºMockMVC对æ¥å£è¿è¡æµè¯ã
ä¸ãåå æµè¯
é¦å åå æµè¯éè¦å¼å ¥Spring Boot Teståæ ï¼å¦ä¸:
org.springframework.boot spring-boot-starter-test test
ç¶åï¼æ°å»ºPackageApplicationTests.javaç±»ï¼å ä¸Spring Bootåå æµè¯æ è¯:
@RunWith(SpringRunner.class)@SpringBootTest
表示æ¯ä¸ä¸ªSpring Bootåå æµè¯ï¼å¹¶å¨æµè¯æ¹æ³ä¸å å ¥@Test声ææµè¯æ¹æ³ï¼å®æ´ä»£ç å¦å¾:
å°é¼ æ 移è³contexrLoadsæ¹æ³ä»£ç åå ï¼å³é®Junitæ§è¡ç»æ:
è¿è¡äºJunitæµè¯æ§è¡ç»æã
äºãMockMvc
ä¸é¢åä¸ä¸MockMvcçæµè¯æ¹æ³ï¼
é¦å ï¼æ°å»ºä¸ä¸ªControllerï¼ä»£ç å¦ä¸:
å¼å ¥MockMvcæä¾å¯¹æ¥å£æµè¯çæ¯æ,æ°å»ºHelloTests.java,å ä¸Spring Bootæµè¯æ å¿:
å¼å ¥MockMvcå·¥å ·:
ç¼ååå æµè¯ç±»åå§åæ¹æ³ï¼å¼å ¥HelloControlleræ¥å£:
æ°å»ºgetHello()åå æµè¯æ¹æ³ï¼å¹¶è®¾ç½®è¯·æ±æ¥å£/helloï¼ä»£ç å¦ä¸:
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("Hello World")));
MockMvcä¼è°ç¨æ¥å£ï¼å¹¶æµè¯æ¥å£æ¯å¦æåï¼æ¥å£è¿åå¼æ¯å¦æ£ç¡®ï¼å®æ´ä»£ç å¦ä¸:
è¿å ¥getHelloæ¹æ³ä½ï¼å³é®Junitï¼æ¥çç»æ:
ç»æè¿åæ£ç¡®ã
æ¥ä¸æ¥æ¹è¿æµè¯æ¹æ³ï¼å¢å éªè¯controlleræ¯å¦æ£å¸¸ååºå¹¶æå°è¿åç»æï¼æ·»å andDo(MockMvcResultHandlers.print())è¾åºæå°ç»æã
MockMvc代ç å¦ä¸:
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn();
å®æ´æµè¯æ¹æ³ä»£ç å¦ä¸:
éæ°Junitæµè¯,æå°ç»æ:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /hello
Parameters = {}
Headers = {Accept=[application/json]}
Body =
Session Attrs = {}
Handler:
Type = com.ocai.core.test.controller.HelloController
Method = public java.lang.String com.ocai.core.test.controller.HelloController.index()
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[11]}
Content type = application/json;charset=ISO-8859-1
Body = Hello World
Forwarded URL = null
Redirected URL = null
Cookies = []
å¦å¾:
表示请æ±æåã
ä¸ãæå å½ä»¤
è¿å ¥å½ä»¤è¡çé¢(CMD)ä¹å¯ä»¥ï¼cd å°é¡¹ç®æ ¹ç®å½(åpom.xmlå级)ï¼å¦å¾:
æ§è¡å½ä»¤:mvn clean package(ä¼æ§è¡Junitæµè¯ä»£ç )
éæ©:mvn clean package -Dmaven.test.skip=TRUE (忽ç¥Junit Test)
å¦å¾ï¼
è¿è¡ç»æ:
å¨targetç®å½ä¸ä¼çæocai-core-package-2.0-SNAPSHOT.jaræ件:
å½åä¸è¬æ¯ 项ç®å+çæ¬å·.jar
CMDè¿å ¥targetç®å½ï¼è¿è¡jaræ件:java -jar ocai-core-package-2.0-SNAPSHOT.jar
å¦å¾:
æ§è¡ï¼è¿è¡ç»æå¦å¾:
å¯å¨æåï¼8483端å£ã
åãå¯å¨è¯»åä¸åé ç½®æ件
åå¤å¥½å 个applicationé ç½®æ件ï¼å ä¸ç¯å¢åç¼åï¼å¦å¾:
application-dev.ymlèµæºæ件示ä¾å¦ä¸:
å¦æè¦éæ©devç¯å¢èµæºæ件ï¼åå¯å¨å½ä»¤ä¸º:
java -jar ocai-core-package-2.0-SNAPSHOT.jar --spring.profiles.active=devåä¼æ§è¡application-dev.ymlèµæºæ件çé
ç½®ãèµæºæ件ç¨äºå¤ä¸ªä¸åçç¯å¢è¿è¡åæ¢ï¼ä¸åçæºå¨ï¼ç产ç¯å¢ãå¼åç¯å¢ãæµè¯ç¯å¢è¿è¡åæ¢ã
Spring Bootè¿å¯ä»¥éç¨ææwarå æ¹å¼ï¼åé¢ç¬è ä¼å享ã