2026-06-30 24681c81c09022f584a57006f2534b5f74723414
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package cn.iocoder.yudao.module.im.service.websocket;
 
import cn.hutool.core.collection.ListUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
import cn.iocoder.yudao.module.im.enums.ImContentTypeEnum;
import cn.iocoder.yudao.module.im.enums.ImConversationTypeEnum;
import cn.iocoder.yudao.module.im.service.websocket.notification.ImNotificationWebSocketDTO;
import cn.iocoder.yudao.module.im.service.websocket.notification.message.ImGroupMessageNotification;
import cn.iocoder.yudao.module.im.service.websocket.notification.message.ImPrivateMessageNotification;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
 
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.*;
 
/**
 * {@link ImWebSocketServiceImpl} 的单元测试
 *
 * @author 芋道源码
 */
public class ImWebSocketServiceImplTest extends BaseMockitoUnitTest {
 
    @InjectMocks
    private ImWebSocketServiceImpl imWebSocketService;
 
    @Mock
    private WebSocketSenderApi webSocketSenderApi;
 
    @AfterEach
    public void tearDown() {
        // 清理事务同步上下文,避免串扰其它用例
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.clearSynchronization();
        }
    }
 
    // ========== 私聊推送 ==========
 
    @Test
    public void testSendNotificationAsync_private_noTransactionSendsImmediately() {
        try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
            springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(ImWebSocketServiceImpl.class)))
                    .thenReturn(imWebSocketService);
 
            // 准备
            ImPrivateMessageNotification dto = new ImPrivateMessageNotification().setSenderId(1L).setReceiverId(2L)
                    .setType(ImContentTypeEnum.TEXT.getType());
 
            // 调用:无事务,应立即发送
            imWebSocketService.sendNotificationAsync(2L, ImConversationTypeEnum.PRIVATE.getType(),
                    ImContentTypeEnum.TEXT.getType(), dto);
 
            // 断言
            verify(webSocketSenderApi).sendObject(
                    eq(UserTypeEnum.ADMIN.getValue()), eq(2L), eq(ImNotificationWebSocketDTO.TYPE),
                    argThat(actual -> isNotification(actual, ImConversationTypeEnum.PRIVATE,
                            ImContentTypeEnum.TEXT, dto)));
        }
    }
 
    @Test
    public void testSendNotificationAsync_private_inTransactionDeferredUntilCommit() {
        try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
            springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(ImWebSocketServiceImpl.class)))
                    .thenReturn(imWebSocketService);
 
            // 准备:开启事务同步
            TransactionSynchronizationManager.initSynchronization();
            try {
                ImPrivateMessageNotification dto = new ImPrivateMessageNotification().setSenderId(1L).setReceiverId(2L)
                        .setType(ImContentTypeEnum.TEXT.getType());
 
                // 调用
                imWebSocketService.sendNotificationAsync(2L, ImConversationTypeEnum.PRIVATE.getType(),
                        ImContentTypeEnum.TEXT.getType(), dto);
 
                // 断言:事务未提交,未推送
                verify(webSocketSenderApi, never()).sendObject(anyInt(), anyLong(), anyString(), any());
 
                // 模拟事务提交
                List<TransactionSynchronization> syncs =
                        TransactionSynchronizationManager.getSynchronizations();
                assertEquals(1, syncs.size());
                syncs.forEach(TransactionSynchronization::afterCommit);
 
                // 断言:提交后推送
                verify(webSocketSenderApi).sendObject(
                        eq(UserTypeEnum.ADMIN.getValue()), eq(2L), eq(ImNotificationWebSocketDTO.TYPE),
                        argThat(actual -> isNotification(actual, ImConversationTypeEnum.PRIVATE,
                                ImContentTypeEnum.TEXT, dto)));
            } finally {
                TransactionSynchronizationManager.clear();
            }
        }
    }
 
    // ========== 群聊推送 ==========
 
    @Test
    public void testSendNotificationAsync_group_fanOutToAllUsers() {
        try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
            springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(ImWebSocketServiceImpl.class)))
                    .thenReturn(imWebSocketService);
 
            ImGroupMessageNotification dto = new ImGroupMessageNotification();
            dto.setGroupId(10L);
            dto.setSenderId(1L);
            dto.setType(ImContentTypeEnum.TEXT.getType());
 
            imWebSocketService.sendNotificationAsync(ListUtil.of(1L, 2L, 3L),
                    ImConversationTypeEnum.GROUP.getType(), ImContentTypeEnum.TEXT.getType(), dto);
 
            verify(webSocketSenderApi).sendObject(
                    eq(UserTypeEnum.ADMIN.getValue()), eq(1L), eq(ImNotificationWebSocketDTO.TYPE),
                    argThat(actual -> isNotification(actual, ImConversationTypeEnum.GROUP,
                            ImContentTypeEnum.TEXT, dto)));
            verify(webSocketSenderApi).sendObject(
                    eq(UserTypeEnum.ADMIN.getValue()), eq(2L), eq(ImNotificationWebSocketDTO.TYPE),
                    argThat(actual -> isNotification(actual, ImConversationTypeEnum.GROUP,
                            ImContentTypeEnum.TEXT, dto)));
            verify(webSocketSenderApi).sendObject(
                    eq(UserTypeEnum.ADMIN.getValue()), eq(3L), eq(ImNotificationWebSocketDTO.TYPE),
                    argThat(actual -> isNotification(actual, ImConversationTypeEnum.GROUP,
                            ImContentTypeEnum.TEXT, dto)));
        }
    }
 
    @Test
    public void testSendNotificationAsync_group_senderExceptionDoesNotBreakOthers() {
        try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
            springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(ImWebSocketServiceImpl.class)))
                    .thenReturn(imWebSocketService);
 
            ImGroupMessageNotification dto = new ImGroupMessageNotification();
            dto.setGroupId(10L);
            // 给 1 号用户推送时抛异常,不能影响 2/3 号
            doThrow(new RuntimeException("user offline"))
                    .when(webSocketSenderApi).sendObject(anyInt(), eq(1L), anyString(), any());
 
            imWebSocketService.sendNotificationAsync(ListUtil.of(1L, 2L, 3L),
                    ImConversationTypeEnum.GROUP.getType(), ImContentTypeEnum.TEXT.getType(), dto);
 
            // 2L 和 3L 也都被推送
            verify(webSocketSenderApi).sendObject(anyInt(), eq(2L), anyString(), any());
            verify(webSocketSenderApi).sendObject(anyInt(), eq(3L), anyString(), any());
        }
    }
 
    @Test
    public void testDoSendNotification_emptyUserIds_noSend() {
        ImGroupMessageNotification dto = new ImGroupMessageNotification();
        dto.setGroupId(10L);
        dto.setType(ImContentTypeEnum.TEXT.getType());
        ImNotificationWebSocketDTO notification = buildNotification(ImConversationTypeEnum.GROUP,
                ImContentTypeEnum.TEXT, dto);
 
        imWebSocketService.doSendNotification(Collections.emptyList(), notification);
        imWebSocketService.doSendNotification(null, notification);
 
        verifyNoInteractions(webSocketSenderApi);
    }
 
    @Test
    public void testDoSendNotification_distinctUserIds() {
        ImGroupMessageNotification dto = new ImGroupMessageNotification();
        dto.setGroupId(10L);
        dto.setType(ImContentTypeEnum.TEXT.getType());
        ImNotificationWebSocketDTO notification = buildNotification(ImConversationTypeEnum.GROUP,
                ImContentTypeEnum.TEXT, dto);
 
        imWebSocketService.doSendNotification(Arrays.asList(1L, 2L, 1L, null), notification);
 
        verify(webSocketSenderApi).sendObject(
                eq(UserTypeEnum.ADMIN.getValue()), eq(1L), eq(ImNotificationWebSocketDTO.TYPE),
                argThat(actual -> isNotification(actual, ImConversationTypeEnum.GROUP,
                        ImContentTypeEnum.TEXT, dto)));
        verify(webSocketSenderApi).sendObject(
                eq(UserTypeEnum.ADMIN.getValue()), eq(2L), eq(ImNotificationWebSocketDTO.TYPE),
                argThat(actual -> isNotification(actual, ImConversationTypeEnum.GROUP,
                        ImContentTypeEnum.TEXT, dto)));
        verifyNoMoreInteractions(webSocketSenderApi);
    }
 
    @Test
    public void testSendNotificationAsync_private_exceptionSwallowed() {
        try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
            springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(ImWebSocketServiceImpl.class)))
                    .thenReturn(imWebSocketService);
 
            // 准备:sender 抛异常
            ImPrivateMessageNotification dto = new ImPrivateMessageNotification().setSenderId(1L).setReceiverId(2L)
                    .setType(ImContentTypeEnum.TEXT.getType());
            doThrow(new RuntimeException("user offline"))
                    .when(webSocketSenderApi).sendObject(anyInt(), anyLong(), anyString(), any());
 
            // 调用:异常应被吞掉,不向上抛
            imWebSocketService.sendNotificationAsync(2L, ImConversationTypeEnum.PRIVATE.getType(),
                    ImContentTypeEnum.TEXT.getType(), dto);
 
            verify(webSocketSenderApi).sendObject(anyInt(), eq(2L), anyString(), any());
        }
    }
 
    @Test
    public void testSendNotificationAsync_group_singleUserDefaultOverload() {
        try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
            springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(ImWebSocketServiceImpl.class)))
                    .thenReturn(imWebSocketService);
 
            ImGroupMessageNotification dto = new ImGroupMessageNotification();
            dto.setGroupId(10L);
            dto.setType(ImContentTypeEnum.TEXT.getType());
 
            imWebSocketService.sendNotificationAsync(42L, ImConversationTypeEnum.GROUP.getType(),
                    ImContentTypeEnum.TEXT.getType(), dto);
 
            verify(webSocketSenderApi).sendObject(
                    eq(UserTypeEnum.ADMIN.getValue()), eq(42L), eq(ImNotificationWebSocketDTO.TYPE),
                    argThat(actual -> isNotification(actual, ImConversationTypeEnum.GROUP,
                            ImContentTypeEnum.TEXT, dto)));
        }
    }
 
    private static boolean isNotification(Object object, ImConversationTypeEnum conversationType,
                                          ImContentTypeEnum contentType, Object payload) {
        if (!(object instanceof ImNotificationWebSocketDTO notification)) {
            return false;
        }
        return conversationType.getType().equals(notification.getConversationType())
                && contentType.getType().equals(notification.getContentType())
                && payload == notification.getPayload();
    }
 
    private static ImNotificationWebSocketDTO buildNotification(ImConversationTypeEnum conversationType,
                                                                ImContentTypeEnum contentType, Object payload) {
        return new ImNotificationWebSocketDTO()
                .setConversationType(conversationType.getType())
                .setContentType(contentType.getType())
                .setPayload(payload);
    }
 
}