package com.xly.erp.common.exception; import com.xly.erp.common.response.ErrorCode; import org.junit.jupiter.api.Test; 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.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @org.springframework.context.annotation.Import(GlobalExceptionHandlerTest.ThrowingTestController.class) class GlobalExceptionHandlerTest { @Autowired private MockMvc mockMvc; @Test void bizException_locked_returns423_withCode42301() throws Exception { mockMvc.perform(get("/_test/throw/locked")) .andExpect(status().isLocked()) .andExpect(jsonPath("$.code").value(ErrorCode.ACCOUNT_LOCKED)) .andExpect(jsonPath("$.data").doesNotExist()); } @Test void bizException_badCredentials_returns401_withCode40101() throws Exception { mockMvc.perform(get("/_test/throw/bad-credentials")) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.code").value(ErrorCode.BAD_CREDENTIALS)); } @Test void unexpectedException_returns500_doesNotLeakStackTrace() throws Exception { mockMvc.perform(get("/_test/throw/runtime")) .andExpect(status().isInternalServerError()) .andExpect(jsonPath("$.code").value(ErrorCode.INTERNAL_ERROR)) .andExpect(jsonPath("$.message").value(not(containsString("java.")))) .andExpect(jsonPath("$.message").value(not(containsString("Exception")))); } @RestController static class ThrowingTestController { @GetMapping("/_test/throw/locked") public void locked() { throw new BizException(ErrorCode.ACCOUNT_LOCKED, "账号已锁定,请稍后再试"); } @GetMapping("/_test/throw/bad-credentials") public void badCredentials() { throw new BizException(ErrorCode.BAD_CREDENTIALS, "用户名或密码错误"); } @GetMapping("/_test/throw/runtime") public void runtime() { throw new RuntimeException("internal boom java.lang.NullPointerException"); } } }