“mitao”
2026-05-12 5b5553bb13ae1dbd31e0fb7edfadac76c0642a8c
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
package com.tcm.training.admin.common;
 
import org.junit.jupiter.api.Test;
 
import javax.servlet.http.HttpServletRequest;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
 
class GlobalExceptionHandlerTest {
 
    private final GlobalExceptionHandler handler = new GlobalExceptionHandler();
 
    @Test
    void handleIllegalStateShouldReturnBusinessMessage() {
        ApiResponse<Void> response = handler.handleIllegalState(
                new IllegalStateException("短信发送失败,请稍后重试"),
                mockRequest()
        );
 
        assertEquals(500, response.getCode());
        assertEquals("短信发送失败,请稍后重试", response.getMsg());
    }
 
    @Test
    void handleIllegalStateShouldReturnFriendlyFallbackWhenMessageBlank() {
        ApiResponse<Void> response = handler.handleIllegalState(
                new IllegalStateException(" "),
                mockRequest()
        );
 
        assertEquals(500, response.getCode());
        assertEquals("服务器开小差啦,请稍后重试", response.getMsg());
    }
 
    @Test
    void handleExceptionShouldHideInternalMessage() {
        ApiResponse<Void> response = handler.handleException(
                new RuntimeException("database down"),
                mockRequest()
        );
 
        assertEquals(500, response.getCode());
        assertEquals("服务器开小差啦,请稍后重试", response.getMsg());
    }
 
    private HttpServletRequest mockRequest() {
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getMethod()).thenReturn("POST");
        when(request.getRequestURI()).thenReturn("/api/app/auth/sms-code");
        return request;
    }
}