GlobalExceptionHandlerTest.java
2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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");
}
}
}