Skip to content

Commit 9d44bfe

Browse files
committed
✅ test User.setId()제거
1 parent e9131e1 commit 9d44bfe

File tree

4 files changed

+100
-65
lines changed

4 files changed

+100
-65
lines changed

backend/src/main/java/io/f1/backend/domain/game/store/RoomRepositoryImpl.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,4 @@ public void removeRoom(Long roomId) {
3535
roomMap.remove(roomId);
3636
}
3737

38-
// 테스트 전용 메소드
39-
public Room getRoomForTest(Long roomId) {
40-
return roomMap.get(roomId);
41-
}
4238
}

backend/src/test/java/io/f1/backend/domain/game/app/RoomServiceTests.java

Lines changed: 62 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import io.f1.backend.domain.user.entity.User;
1717
import io.f1.backend.global.util.SecurityUtils;
1818

19+
import java.lang.reflect.Field;
1920
import lombok.extern.slf4j.Slf4j;
2021

2122
import org.junit.jupiter.api.AfterEach;
@@ -44,18 +45,24 @@ class RoomServiceTests {
4445

4546
private RoomService roomService;
4647

47-
@Mock private RoomRepository roomRepository;
48-
@Mock private QuizService quizService;
49-
@Mock private TimerService timerService;
50-
@Mock private ApplicationEventPublisher eventPublisher;
51-
@Mock private MessageSender messageSender;
48+
@Mock
49+
private RoomRepository roomRepository;
50+
@Mock
51+
private QuizService quizService;
52+
@Mock
53+
private TimerService timerService;
54+
@Mock
55+
private ApplicationEventPublisher eventPublisher;
56+
@Mock
57+
private MessageSender messageSender;
5258

5359
@BeforeEach
5460
void setUp() {
5561
MockitoAnnotations.openMocks(this); // @Mock 어노테이션이 붙은 필드들을 초기화합니다.
62+
5663
roomService =
57-
new RoomService(
58-
timerService, quizService, roomRepository, eventPublisher, messageSender);
64+
new RoomService(
65+
timerService, quizService, roomRepository, eventPublisher, messageSender);
5966

6067
SecurityContextHolder.clearContext();
6168
}
@@ -83,21 +90,22 @@ void enterRoom_synchronized() throws Exception {
8390
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
8491
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
8592
RoomValidationRequest roomValidationRequest = new RoomValidationRequest(roomId, password);
93+
8694
for (int i = 1; i <= threadCount; i++) {
8795
User user = createUser(i);
8896

8997
executorService.submit(
90-
() -> {
91-
try {
92-
SecurityUtils.setAuthentication(user);
93-
roomService.enterRoom(roomValidationRequest);
94-
} catch (Exception e) {
95-
e.printStackTrace();
96-
} finally {
97-
SecurityContextHolder.clearContext();
98-
countDownLatch.countDown();
99-
}
100-
});
98+
() -> {
99+
try {
100+
SecurityUtils.setAuthentication(user);
101+
roomService.enterRoom(roomValidationRequest);
102+
} catch (Exception e) {
103+
e.printStackTrace();
104+
} finally {
105+
SecurityContextHolder.clearContext();
106+
countDownLatch.countDown();
107+
}
108+
});
101109
}
102110
countDownLatch.await();
103111
assertThat(room.getCurrentUserCnt()).isEqualTo(room.getRoomSetting().maxUserCount());
@@ -113,6 +121,7 @@ void exitRoom_synchronized() throws Exception {
113121
String password = "123";
114122
boolean locked = true;
115123

124+
/* 방 생성 */
116125
Room room = createRoom(roomId, playerId, quizId, password, maxUserCount, locked);
117126

118127
int threadCount = 10;
@@ -128,6 +137,7 @@ void exitRoom_synchronized() throws Exception {
128137
Player host = players.getFirst();
129138
room.updateHost(host);
130139

140+
/* 방 입장 */
131141
for (int i = 1; i <= threadCount; i++) {
132142
String sessionId = "sessionId" + i;
133143
Player player = players.get(i - 1);
@@ -141,36 +151,37 @@ void exitRoom_synchronized() throws Exception {
141151
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
142152
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
143153

154+
/* 방 퇴장 테스트 */
144155
for (int i = 1; i <= threadCount; i++) {
145156
String sessionId = "sessionId" + i;
146157
User user = createUser(i);
147158
executorService.submit(
148-
() -> {
149-
try {
150-
UserPrincipal principal =
151-
new UserPrincipal(user, Collections.emptyMap());
152-
SecurityUtils.setAuthentication(user);
153-
log.info("room.getHost().getId() = {}", room.getHost().getId());
154-
roomService.exitRoom(roomId, sessionId, principal);
155-
} catch (Exception e) {
156-
e.printStackTrace();
157-
} finally {
158-
SecurityContextHolder.clearContext();
159-
countDownLatch.countDown();
160-
}
161-
});
159+
() -> {
160+
try {
161+
UserPrincipal principal =
162+
new UserPrincipal(user, Collections.emptyMap());
163+
SecurityUtils.setAuthentication(user);
164+
log.info("room.getHost().getId() = {}", room.getHost().getId());
165+
roomService.exitRoom(roomId, sessionId, principal);
166+
} catch (Exception e) {
167+
e.printStackTrace();
168+
} finally {
169+
SecurityContextHolder.clearContext();
170+
countDownLatch.countDown();
171+
}
172+
});
162173
}
163174
countDownLatch.await();
164175
verify(roomRepository).removeRoom(roomId);
165176
}
166177

167178
private Room createRoom(
168-
Long roomId,
169-
Long playerId,
170-
Long quizId,
171-
String password,
172-
int maxUserCount,
173-
boolean locked) {
179+
Long roomId,
180+
Long playerId,
181+
Long quizId,
182+
String password,
183+
int maxUserCount,
184+
boolean locked) {
174185
RoomSetting roomSetting = new RoomSetting("방제목", maxUserCount, locked, password);
175186
GameSetting gameSetting = new GameSetting(quizId, 10, 60);
176187
Player host = new Player(playerId, "nickname");
@@ -185,12 +196,19 @@ private User createUser(int i) {
185196
LocalDateTime lastLogin = LocalDateTime.now();
186197

187198
User user =
188-
User.builder()
189-
.provider(provider)
190-
.providerId(providerId)
191-
.lastLogin(lastLogin)
192-
.build();
193-
user.setId(userId);
199+
User.builder()
200+
.provider(provider)
201+
.providerId(providerId)
202+
.lastLogin(lastLogin)
203+
.build();
204+
205+
try {
206+
Field idField = User.class.getDeclaredField("id");
207+
idField.setAccessible(true);
208+
idField.set(user, userId);
209+
} catch (Exception e) {
210+
throw new RuntimeException("ID 설정 실패", e);
211+
}
194212

195213
return user;
196214
}

backend/src/test/java/io/f1/backend/domain/game/store/RoomRepositoryTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ void saveRoom_test() {
5252

5353
roomRepository.saveRoom(newRoom);
5454

55-
Room savedRoom = roomRepository.getRoomForTest(newId);
55+
Room savedRoom = roomRepository.findRoom(newId).orElseThrow();
5656

5757
assertThat(savedRoom.getHost().getId()).isEqualTo(loginUser.get("id"));
5858
assertThat(savedRoom.getHost().getNickname()).isEqualTo(loginUser.get("nickname"));

backend/src/test/java/io/f1/backend/domain/game/websocket/SessionServiceTests.java

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package io.f1.backend.domain.game.websocket;
22

3-
import static org.junit.jupiter.api.Assertions.*;
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
5+
import static org.junit.jupiter.api.Assertions.assertNull;
6+
import static org.junit.jupiter.api.Assertions.assertTrue;
47
import static org.mockito.ArgumentMatchers.any;
58
import static org.mockito.ArgumentMatchers.anyLong;
69
import static org.mockito.ArgumentMatchers.anyString;
@@ -14,7 +17,12 @@
1417
import io.f1.backend.domain.game.websocket.service.SessionService;
1518
import io.f1.backend.domain.user.dto.UserPrincipal;
1619
import io.f1.backend.domain.user.entity.User;
17-
20+
import java.lang.reflect.Field;
21+
import java.time.LocalDateTime;
22+
import java.util.HashMap;
23+
import java.util.Map;
24+
import java.util.concurrent.ConcurrentHashMap;
25+
import java.util.concurrent.Executors;
1826
import org.junit.jupiter.api.BeforeEach;
1927
import org.junit.jupiter.api.DisplayName;
2028
import org.junit.jupiter.api.Test;
@@ -24,12 +32,6 @@
2432
import org.mockito.junit.jupiter.MockitoExtension;
2533
import org.springframework.test.util.ReflectionTestUtils;
2634

27-
import java.time.LocalDateTime;
28-
import java.util.HashMap;
29-
import java.util.Map;
30-
import java.util.concurrent.ConcurrentHashMap;
31-
import java.util.concurrent.Executors;
32-
3335
@ExtendWith(MockitoExtension.class)
3436
class SessionServiceTests {
3537

@@ -41,9 +43,7 @@ class SessionServiceTests {
4143
private String sessionId1 = "session1";
4244
private String sessionId2 = "session2";
4345
private Long userId1 = 100L;
44-
private Long userId2 = 200L;
4546
private Long roomId1 = 1L;
46-
private Long roomId2 = 2L;
4747

4848
@BeforeEach
4949
void setUp() {
@@ -95,8 +95,7 @@ void handleUserDisconnect_shouldExitIfNotPlayingIfDisconnected() throws Interrup
9595
sessionService.addRoomId(roomId1, sessionId1);
9696
sessionService.addSession(sessionId1, userId1);
9797

98-
User user = new User("provider", "providerId", LocalDateTime.now());
99-
user.setId(userId1);
98+
User user = createUser(1);
10099
UserPrincipal principal = new UserPrincipal(user, new HashMap<>());
101100

102101
// disconnect 호출
@@ -154,8 +153,7 @@ void handleUserDisconnect_shouldStoreOldSessionIdInLatestSession() {
154153
sessionService.addSession(sessionId1, userId1); // 유저의 현재 활성 세션
155154
sessionService.addRoomId(roomId1, sessionId1);
156155

157-
User user = new User("provider", "providerId", LocalDateTime.now());
158-
user.setId(userId1);
156+
User user = createUser(1);
159157
UserPrincipal principal = new UserPrincipal(user, new HashMap<>());
160158

161159
// when
@@ -183,8 +181,7 @@ void handleUserDisconnect_reconnectWithin5Seconds_shouldCleanLatestSession()
183181
sessionService.addSession(sessionId1, userId1); // 초기 세션
184182
sessionService.addRoomId(roomId1, sessionId1);
185183

186-
User user = new User("provider", "providerId", LocalDateTime.now());
187-
user.setId(userId1);
184+
User user = createUser(1);
188185
UserPrincipal principal = new UserPrincipal(user, new HashMap<>());
189186

190187
sessionService.handleUserDisconnect(
@@ -231,4 +228,28 @@ void handleUserDisconnect_reconnectWithin5Seconds_shouldCleanLatestSession()
231228
assertTrue(sessionIdRoom.containsKey(sessionId2));
232229
assertEquals(roomId1, sessionIdRoom.get(sessionId2));
233230
}
231+
232+
private User createUser(int i) {
233+
Long userId = i + 1L;
234+
String provider = "provider +" + i;
235+
String providerId = "providerId" + i;
236+
LocalDateTime lastLogin = LocalDateTime.now();
237+
238+
User user =
239+
User.builder()
240+
.provider(provider)
241+
.providerId(providerId)
242+
.lastLogin(lastLogin)
243+
.build();
244+
245+
try {
246+
Field idField = User.class.getDeclaredField("id");
247+
idField.setAccessible(true);
248+
idField.set(user, userId);
249+
} catch (Exception e) {
250+
throw new RuntimeException("ID 설정 실패", e);
251+
}
252+
253+
return user;
254+
}
234255
}

0 commit comments

Comments
 (0)