單元測試,全局異常
一、單元測試
1.基礎版
1、引入相關依賴
<!--springboot程序測試依賴,如果是自動創建項目默認添加--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2:關鍵注解:@RunWith @SpringBootTest
import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner @SpringBootTest(classes={SpringbootstudyApplication.class})//啟動整個springboot工程 public class SpringBootTestDemo { @Test public void testOne(){ System.out.println("test hello 1"); TestCase.assertEquals(1, 1); } @Test public void testTwo(){ System.out.println("test hello 2"); TestCase.assertEquals(1, 1); } @Before public void testBefore(){ System.out.println("before"); } @After public void testAfter(){ System.out.println("after"); } }
輸出結果:
2.MockMvc
MockMvc類的使用和模擬Http請求實戰
TestController
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping("/vq/test") public String getTest(){ return"我是測試返回值"; } }
MockMvcTestDemo
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; /** * 功能描述:測試mockmvc類 * */ @RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner @SpringBootTest(classes={SpringbootstudyApplication.class}) //啟動整個springboot工程 @AutoConfigureMockMvc public class MockMvcTestDemo { @Autowired private MockMvc mockMvc; @Test public void apiTest() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/vq/test") ). andExpect( MockMvcResultMatchers.status().isOk() ).andReturn(); int status = mvcResult.getResponse().getStatus(); System.out.println(status); } }
結果:返回200狀態碼
總結,關鍵注解:
@RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={SpringbootstudyApplication.class}) //啟動整個springboot工程
@AutoConfigureMockMvc
二、配置全局異常
首先springboot自帶異常是不友好的。
舉例
@RequestMapping(value = "/api/v1/test_ext") public Object index() { int i= 1/0; return new User(11, "sfsfds", "1000000", new Date()); }
頁面
1、配置全局異常
import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; //添加全局異常注解 @RestControllerAdvice public class CustomExtHandler { private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); //捕獲全局異常,處理所有不可知的異常 @ExceptionHandler(value=Exception.class) //@ResponseBody Object handleException(Exception e,HttpServletRequest request){ LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); Map<String, Object> map = new HashMap<>(); map.put("code", 100); map.put("msg", e.getMessage()); map.put("url", request.getRequestURL()); return map; } }
在看頁面:
關鍵注解:
@RestControllerAdvice //全局注解
@ExceptionHandler(value=Exception.class) //捕獲不同異常,這里捕獲是Exception異常,你也可以指定其它異常
2.自定義異常
在 Java 中你可以自定義異常。編寫自己的異常類時需要記住下面的幾點。
- 所有異常都必須是 Throwable 的子類。
- 如果希望寫一個檢查性異常類,則需要繼承 Exception 類。
- 如果你想寫一個運行時異常類,那么需要繼承 RuntimeException 類。
1.自定義MyException異常
/** * 功能描述:自定義異常類 * */ public class MyException extends RuntimeException { private static final long serialVersionUID = 1L; public MyException(String code, String msg) { this.code = code; this.msg = msg; } private String code; private String msg; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
controller類
/** * 功能描述:模擬自定義異常 */ @RequestMapping("/api/v1/myext") public Object myexc(){ //直接拋出異常 throw new MyException("499", "my ext異常"); }
頁面
想太多,做太少,中間的落差就是煩惱。想沒有煩惱,要么別想,要么多做。上尉【7】