詳解SpringBoot項目的創建與單元測試
Spring Boot 設計之初就是為了用最少的配置,以最快的速度來啟動和運行 Spring 項目。Spring Boot使用特定的配置來構建生產就緒型的項目。
Hello World1.可以在 Spring Initializr上面添加,也可以手動在 pom.xml中添加如下代碼∶<dependency> <groupId>org.springframework.boot</groupId> <artifactId>Spring-boot-starter-web</artifactId></dependency>
pom.xml 文件中默認有個模塊∶
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency>
<scope>test</scope>表示依賴的組件僅僅參與測試相關的工作,包括測試代碼的編譯和執行,不會被打包包含進去;spring-boot-starter-test 是 Spring Boot 提供項目測試的工具包,內置了多種測試工具,方便我們在項目中做單元測試、集成測試。
2. 編寫 Controller 內容在目錄 srcmainjava下新建一個包:com.reminis.web,然后在該包下創建 HelloController∶
@RestControler 的意思是 Contoller 里面的方法都以JSON格式輸出,不需要有其他額外的配置;如果配置為@Controller,代表輸出內容到頁面。@RequestMapping('hello')提供路由信息,'hello'路徑的HTTP Request 都會被映射到hello()方法上進行處理。啟動主程序右鍵單擊項目中的 DemoAppicationrun命令,就可以啟動項目了,若出現以下內容表示啟動成功∶
@RestControllerpublic class HelloController { @RequestMapping('/hello') public String hello(){ return 'hello world'; } } @RestControler 的意思是 Contoller 里面的方法都以JSON格式輸出,不需要有其他額外的配置;如果配置為@Controller,代表輸出內容到頁面。 @RequestMapping('hello')提供路由信息,'hello'路徑的HTTP Request 都會被映射到hello()方法上進行處理。 3.啟動主程序
右鍵單擊項目中的 DemoAppicationrun命令,就可以啟動項目了,若出現以下內容表示啟動成功∶
如果啟動過程中出現javaClassNotFoundException 異常,請檢查 M aven 配置是否正確,具體如下:
檢查 Maven 的 settigs.xml文件是否引入正確。 檢查 IDE 工具中的 Maven插件是否配置為本機的 Maven地址,如下圖Spring Boot 還提供了另外兩種啟動項目的方式∶
在項目路徑下,使用命令行mvnspring-boot∶run來啟動,其效果和上面'啟動主程序'的效果是一致的; 或者將項目打包,打包后以Jar 包的形式來啟動。# 進行項目根目錄 cd ../demo # 執行打包命令 mvn clean package # 以 Jar 包的形式啟動 java -jar target/hello-0.0.1-SNAPSHOT.jar
啟動成功后,打開瀏覽器輸入網址∶http∶//localhost:8080/hello, 就可以看到以下內容了∶
開發階段建議使用第一種方式啟動,便于開發過程中調試。
4. 如果我們想傳入參數怎么辦?請求傳參一般分為URL地址傳參和表單傳參兩種方式,兩者各有優缺點,但基本都以鍵值對的方式將參數傳遞到后端。作為后端程序不用關注前端采用的那種方式,只需要根據參數的鍵來獲取值,Spring提供了很多種參數接收方式,本章我們了解最簡單的方式∶通過 URL傳參。只要后端處理請求的方法中存在參數鍵相同名稱的屬性,在請求的過程中Spring會自動將參數值賦值到屬性中,最后在方法中直接使用即可。下面我們以 hello()為例進行演示。
@RestControllerpublic class HelloController { @RequestMapping('/hello') public String hello(String name) { System.out.println('name...' + name); return 'hello world, ' + name; }}
重新啟動項目,打開瀏覽器輸入網址 http∶//localhost8080/hello?name=reminis,返回如下內容:
到這里,我們的第一個 Spring Boot項目就開發完成了,有沒有感覺很簡單?經過測試發現,修改Controllr內相關的代碼,需要重新啟動項目才能生效,這樣做很麻煩是不是?別著急,Spring Boot又給我們提供了另外一個組件來解決。
熱部署熱啟動就需要用到一個組件∶spring-boot-devtools。它是 Spring Boot 提供的一組開發工具包,其中就包含我們需要的熱部署功能,在使用這個功能之前還需要再做一些配置。
添加依賴在 pom.xml文件中添加 spring-boot-devtools 組件。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
在 plugin 中配置另外一個屬性 fork,并且配置為 true。
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
OK,以上的配置就完成了,如果你使用的是 Eclipse 集成開發環境,那么恭喜你大功告成了;如果你使用的是 IDEA 集成開發環境,那么還需要做以下配置。配置 IDEA選擇 File-Settings-Compiler 命令,然后勾選 Build project automati cally復選框,低版本的 IDEA請勾選make project automatically 復選框。
使用快捷鍵Ctrl+Shift+A,在輸入框中輸入 Registry,勾選 復選框∶
全部配置完成后,IDEA 就支持熱部署了,大家可以試著去改動一下代碼,等待5秒就會發現 Spring Boot會自動重新加載,再也不需要手動單擊重新啟動了。
為什么 IDEA需要多配置后面這一步呢?因為 IDEA默認不是自動編譯的,需要我們手動去配置后才會自動編譯,而熱部署依賴于項目的自動編譯功能。該模塊在完整的打包環境下運行的時候會被禁用,如果你使用 java-jar 啟動應用或者用一個特定的classloader 啟動,它會認為這是一個'生產環境'。
單元測試單元測試在我們日常開發中必不可少,一個優秀的程序員,單元測試開發也非常完善。下面我們看下 Spring Boot 對單元測試又做了哪些支持?
如果我們只想運行一個hello world,只需要一個@Test 注解就可以了。在src/test 目錄下新建一個 HelloTest類,代碼如下∶
public class HelloTest { @Test private void hello() { System.out.println('hello world'); }}
右鍵單擊'運行'按鈕,發現控制臺會輸出∶hello world。如果需要測試 Web 層的請求呢? Spring Boot 也給出了支持。以往我們在測試 Web 請求的時候,需要手動輸入相關參數在頁面測試查看效果,或者自己寫post 請求。在 Spring Boot體系中,Spring 給出了一個簡單的解決方案,使用 MockMVC進行 Web測試, MockMVC內置了很多工具類和方法,可以模擬 post、get 請求,并且判斷返回的結果是否正確等,也可以利用 print()打印執行結果。
@SpringBootTest(classes = DemoApplication.class)class DemoApplicationTests { private MockMvc mockMvc; @BeforeEach public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()).build(); } @Test public void getHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders .post('/hello?name=reminis') .accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultHandlers.print()); }}
@BeforeEach注解的方法表示在測試啟動的時候優先執行,一般用作資源初始化。由于我的SpringBoot項目版本是2.4.3,集成的是Junit5,JUnit5的環境下, @BeforeEach 和@AfterEach去替代@Before和@After注解。Junit4是使用@Before和@After注解.
在類的上面添加@SpringBootTest,系統會自動加載 Spring Boot 容器。在日常測試中,可以注入bean 來做一些局部的業務測試。MockMvcRequestBuilders 可以支持 post、get 請求,使用 MockMvcResultHandlers.print() 方法會將請求和相應的過程都打印出來,具體如下∶
MockHttpServletRequest: HTTP Method = POST Request URI = /hello Parameters = {name=[reminis]} Headers = [Accept:'application/json'] Body = <no character encoding set> Session Attrs = {}Handler: Type = com.reminis.demo.controller.HelloController Method = com.reminis.demo.controller.HelloController#hello(String)Async: Async started = false Async result = nullResolved Exception: Type = nullModelAndView: View name = null View = null Model = nullFlashMap: Attributes = nullMockHttpServletResponse: Status = 200 Error message = null Headers = [Content-Type:'application/json', Content-Length:'20'] Content type = application/json Body = hello world, reminis Forwarded URL = null Redirected URL = null Cookies = [] Type = nullModelAndView: View name = null View = null Model = nullFlashMap: Attributes = nullMockHttpServletResponse: Status = 200 Error message = null Headers = [Content-Type:'application/json', Content-Length:'20'] Content type = application/json Body = hello world, reminis Forwarded URL = null Redirected URL = null Cookies = []
從返回的Body= hello world ,reminis可以看出請求成功了。當然每次請求都看這么多返回結果,不太容易識別,MockMVC提供了更多方法來判斷返回結果,其中就有判斷返回值。我們將上面的 getHello()方法稍稍進行改造,具體如下所示∶
@Test public void getHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders .post('/hello?name=reminis') .accept(MediaType.APPLICATION_JSON)) /*.andDo(MockMvcResultHandlers.print())*/ .andExpect(MockMvcResultMatchers.content(). string(Matchers.containsString('reminis'))); }
MockMvcResultMatchers.content()這段代碼的意思是獲取到 Wceb 請求執行后的結果;Matchers.contansString('reminis'),判斷返回的結果集中是否包含'reminis'這個字符串.
我們簡單做一下對比,使用Spring Boot之前和使用之后。使用 Spring Boot 前∶
配置 web.xml,加載Spring和 Spring MVC 配置數據庫連接、配置 Spring 事務 配置加載配置文件的讀取,開啟注解 配置日志文件 配置完成之后部署 Tomcat 調試 使用Spring Boot之后,僅僅三步即可快速搭建起一個Web項目∶ 頁面配置導入到開發工具中 進行代碼編寫 運行通過對比可以發現Spring Boot在開發階段做了大量優化,非常容易快速構建一個項目。
以上就是詳解SpringBoot項目的創建與單元測試的詳細內容,更多關于SpringBoot項目創建與單元測試的資料請關注好吧啦網其它相關文章!
相關文章: