#SpringBoot# Springboot2.0單元測試和自定義異常處理

SpringBootTest單元測試

//1、引入相關依賴
 <!--springboot程序測試依賴,如果是自動創建項目默認添加-->
 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
//使用
@RunWith(SpringRunner.class)  //底層用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//啓動整個springboot工程
public class SpringBootTests { }

SpringBoot測試之MockMvc講解

MockMvc類的使用和模擬Http請求實戰

  • 1、增加類註解 @AutoConfigureMockMvc @SpringBootTest(classes={XdclassApplication.class})
  • 2、相關API perform:執行一個RequestBuilder請求 andExpect:添加ResultMatcher->MockMvcResultMatchers驗證規則 andReturn:最後返回相應的MvcResult->Response

SpringBoot個性化啓動banner設置和debug日誌

自定義應用啓動的趣味性日誌圖標和查看調試日誌
1、啓動獲取更多信息 java -jar xxx.jar --debug

2、修改啓動的banner信息
	1)在類路徑下增加一個banner.txt,裏面是啓動要輸出的信息
	2)在applicatoin.properties增加banner文件的路徑地址 
		spring.banner.location=banner.txt

	3)官網地址 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-banners

SpringBoot2.x配置全局異常

服務端異常講解和SpringBoot配置全局異常
1、默認異常測試 int i = 1/0,不友好

2、異常註解介紹
@ControllerAdvice 如果是返回json數據 則用 RestControllerAdvice,就可以不加 @ResponseBody

//捕獲全局異常,處理所有不可知的異常
@ExceptionHandler(value=Exception.class)

SpringBoot2.x配置全局異常返回自定義頁面

使用SpringBoot自定義異常和錯誤頁面跳轉實戰

1、返回自定義異常界面,需要引入thymeleaf依賴
	<dependency>
	   <groupId>org.springframework.boot</groupId>
	   <artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
2、resource目錄下新建templates,並新建error.html
	ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error.html");
    modelAndView.addObject("msg", e.getMessage());
    return modelAndView;
https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling

在這裏插入圖片描述
公衆號: 自學it的攻城獅(id:study458)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章