springboot(5)單元測試及MockMVC類的使用及自定義異常處理


springboot @SpringBootTest單元測試
1、引入相關依賴
<!--springboot程序測試依賴,如果是自動創建項目默認添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>


2、使用
@RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//啟動整個springboot工程
public class SpringBootTests { }

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


springboot2.x配置全局異常處理
1、默認異常測試 int i = 1/0,不友好

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

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

springboot2.x自定義全局異常
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM