Skip to content

Commit 46df050

Browse files
committed
[Feat]: 응답 형태 변경에 따른 PostControllerTest 수정
1 parent 92de9fe commit 46df050

File tree

1 file changed

+133
-28
lines changed

1 file changed

+133
-28
lines changed

back/src/test/java/com/back/domain/post/controller/PostControllerTest.java

Lines changed: 133 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.back.domain.post.controller;
22

33
import com.back.domain.post.dto.PostRequest;
4-
import com.back.domain.post.dto.PostResponse;
54
import com.back.domain.post.entity.Post;
65
import com.back.domain.post.enums.PostCategory;
76
import com.back.domain.post.repository.PostRepository;
@@ -22,16 +21,14 @@
2221
import org.springframework.http.HttpStatus;
2322
import org.springframework.http.MediaType;
2423
import org.springframework.test.context.ActiveProfiles;
24+
import org.springframework.test.context.jdbc.Sql;
2525
import org.springframework.test.web.servlet.MockMvc;
26-
import org.springframework.test.web.servlet.MvcResult;
2726
import org.springframework.transaction.annotation.Transactional;
2827

2928
import java.time.LocalDateTime;
3029
import java.util.stream.IntStream;
3130

32-
import static org.assertj.core.api.Assertions.assertThat;
33-
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
34-
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
31+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
3532
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
3633
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
3734

@@ -53,9 +50,12 @@ class PostControllerTest {
5350
@Autowired
5451
private UserRepository userRepository;
5552

53+
private User testUser;
54+
private User anotherUser;
55+
5656
@BeforeEach
5757
void setUp() {
58-
User testUser = User.builder()
58+
testUser = User.builder()
5959
.loginId("testLoginId")
6060
6161
.password("testPassword")
@@ -67,6 +67,18 @@ void setUp() {
6767
.build();
6868
userRepository.save(testUser);
6969

70+
anotherUser = User.builder()
71+
.loginId("anotherLoginId")
72+
73+
.password("another")
74+
.beliefs("도전")
75+
.gender(Gender.F)
76+
.role(Role.USER)
77+
.mbti(Mbti.ISFJ)
78+
.birthdayAt(LocalDateTime.of(2001, 4, 1, 0, 0))
79+
.build();
80+
userRepository.save(anotherUser);
81+
7082
IntStream.rangeClosed(1, 5).forEach(i -> {
7183
postRepository.save(
7284
Post.builder()
@@ -90,22 +102,15 @@ void success() throws Exception {
90102
PostRequest request = new PostRequest("테스트 게시글", "테스트 내용입니다.", PostCategory.CHAT);
91103

92104
// when
93-
MvcResult result = mockMvc.perform(post("/api/v1/posts")
105+
mockMvc.perform(post("/api/v1/posts")
94106
.contentType(MediaType.APPLICATION_JSON)
95107
.content(objectMapper.writeValueAsString(request)))
96-
.andExpect(status().isCreated())
97-
.andExpect(jsonPath("$.title").value("테스트 게시글"))
98-
.andExpect(jsonPath("$.content").value("테스트 내용입니다."))
99-
.andExpect(jsonPath("$.category").value("CHAT"))
100-
.andReturn();
101-
102-
String responseBody = result.getResponse().getContentAsString();
103-
PostResponse response = objectMapper.readValue(responseBody, PostResponse.class);
104-
105-
Post savedPost = postRepository.findById(response.id()).orElseThrow();
106-
assertThat(savedPost.getTitle()).isEqualTo("테스트 게시글");
107-
assertThat(savedPost.getContent()).isEqualTo("테스트 내용입니다.");
108-
assertThat(savedPost.getCategory()).isEqualTo(PostCategory.CHAT);
108+
.andExpect(status().isOk())
109+
.andExpect(jsonPath("$.data.title").value("테스트 게시글"))
110+
.andExpect(jsonPath("$.data.content").value("테스트 내용입니다."))
111+
.andExpect(jsonPath("$.data.category").value("CHAT"))
112+
.andExpect(jsonPath("$.message").value("성공적으로 생성되었습니다."))
113+
.andExpect(jsonPath("$.status").value(200));
109114
}
110115

111116
@Test
@@ -144,9 +149,11 @@ void success() throws Exception {
144149
// when & then
145150
mockMvc.perform(get("/api/v1/posts/{postId}", savedPost.getId()))
146151
.andExpect(status().isOk())
147-
.andExpect(jsonPath("$.title").value("조회 테스트 게시글"))
148-
.andExpect(jsonPath("$.content").value("조회 테스트 내용입니다."))
149-
.andExpect(jsonPath("$.category").value("CHAT"));
152+
.andExpect(jsonPath("$.data.title").value("조회 테스트 게시글"))
153+
.andExpect(jsonPath("$.data.content").value("조회 테스트 내용입니다."))
154+
.andExpect(jsonPath("$.data.category").value("CHAT"))
155+
.andExpect(jsonPath("$.status").value(200))
156+
.andExpect(jsonPath("$.message").value("성공적으로 조회되었습니다."));
150157
}
151158

152159
@Test
@@ -167,14 +174,112 @@ void fail_NotFound() throws Exception {
167174
class GetPosts {
168175

169176
@Test
170-
@DisplayName("성공 - 게시글 목록 조회")
171-
void success() throws Exception {
177+
@DisplayName("성공 - 페이징 파라미터가 없는 경우")
178+
void successWithDefaultParameters() throws Exception {
172179
// when & then
173180
mockMvc.perform(get("/api/v1/posts"))
174181
.andExpect(status().isOk())
175-
.andExpect(jsonPath("$.length()").value(5))
176-
.andExpect(jsonPath("$[0].title").value("목록 게시글 1"))
177-
.andExpect(jsonPath("$[1].title").value("목록 게시글 2"));
182+
.andExpect(jsonPath("$.data.page").value(1))
183+
.andExpect(jsonPath("$.data.size").value(5))
184+
.andExpect(jsonPath("$.status").value(200))
185+
.andExpect(jsonPath("$.message").value("성공적으로 조회되었습니다."));
186+
}
187+
188+
@Test
189+
@DisplayName("성공 - page와 size 모두 지정")
190+
void successWithBothParameters() throws Exception {
191+
// when & then
192+
mockMvc.perform(get("/api/v1/posts")
193+
.param("page", "1")
194+
.param("size", "5"))
195+
.andExpect(status().isOk())
196+
.andExpect(jsonPath("$.data.items.length()").value(5))
197+
.andExpect(jsonPath("$.data.items[0].title").value("목록 게시글 1"))
198+
.andExpect(jsonPath("$.data.items[1].title").value("목록 게시글 2"))
199+
.andExpect(jsonPath("$.data.page").value(1))
200+
.andExpect(jsonPath("$.data.size").value(5))
201+
.andExpect(jsonPath("$.data.totalElements").value(5))
202+
.andExpect(jsonPath("$.data.totalPages").value(1))
203+
.andExpect(jsonPath("$.data.last").value(true))
204+
.andExpect(jsonPath("$.status").value(200))
205+
.andExpect(jsonPath("$.message").value("성공적으로 조회되었습니다."));
206+
}
207+
208+
@Test
209+
@DisplayName("성공 - 정렬 파라미터 포함")
210+
void successWithSortParameters() throws Exception {
211+
// when & then
212+
mockMvc.perform(get("/api/v1/posts")
213+
.param("page", "1")
214+
.param("size", "5")
215+
.param("sort", "createdDate,desc")
216+
.param("sort", "title,asc"))
217+
.andExpect(status().isOk())
218+
.andExpect(jsonPath("$.data.page").value(1))
219+
.andExpect(jsonPath("$.data.size").value(5))
220+
.andExpect(jsonPath("$.status").value(200));
221+
}
222+
}
223+
224+
@Nested
225+
@DisplayName("게시글 수정")
226+
class UpdatePost {
227+
228+
@Test
229+
@DisplayName("성공 - 본인 게시글 수정")
230+
@Sql(statements = {
231+
"UPDATE users SET id = 1 WHERE login_id = 'testLoginId'"
232+
})
233+
void success() throws Exception {
234+
// given - ID=1인 사용자의 게시글 생성
235+
User user1 = userRepository.findById(1L).orElseThrow();
236+
Post savedPost = postRepository.save(
237+
Post.builder()
238+
.title("수정 전 제목")
239+
.content("수정 전 내용")
240+
.category(PostCategory.CHAT)
241+
.user(user1)
242+
.build()
243+
);
244+
245+
PostRequest updateRequest = new PostRequest("수정된 제목", "수정된 내용", PostCategory.CHAT);
246+
247+
// when & then
248+
mockMvc.perform(put("/api/v1/posts/{postId}", savedPost.getId())
249+
.contentType(MediaType.APPLICATION_JSON)
250+
.content(objectMapper.writeValueAsString(updateRequest)))
251+
.andExpect(status().isOk())
252+
.andExpect(jsonPath("$.data.title").value("수정된 제목"))
253+
.andExpect(jsonPath("$.data.content").value("수정된 내용"))
254+
.andExpect(jsonPath("$.data.category").value("CHAT"));
255+
}
256+
257+
@Test
258+
@DisplayName("실패 - 다른 사용자 게시글 수정")
259+
@Sql(statements = {
260+
"UPDATE users SET id = 1 WHERE login_id = 'testLoginId'",
261+
"UPDATE users SET id = 2 WHERE login_id = 'anotherLoginId'"
262+
})
263+
void fail_UnauthorizedUser() throws Exception {
264+
// given - ID=2인 사용자의 게시글 (ID=1 사용자가 수정 시도)
265+
User user2 = userRepository.findById(2L).orElseThrow();
266+
Post savedPost = postRepository.save(
267+
Post.builder()
268+
.title("다른 사용자 게시글")
269+
.content("다른 사용자 내용")
270+
.category(PostCategory.CHAT)
271+
.user(user2)
272+
.build()
273+
);
274+
275+
PostRequest updateRequest = new PostRequest("수정 시도", "수정 시도 내용", PostCategory.CHAT);
276+
277+
// when & then
278+
mockMvc.perform(put("/api/v1/posts/{postId}", savedPost.getId())
279+
.contentType(MediaType.APPLICATION_JSON)
280+
.content(objectMapper.writeValueAsString(updateRequest)))
281+
.andExpect(status().isUnauthorized())
282+
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED_USER.getCode()));
178283
}
179284
}
180285
}

0 commit comments

Comments
 (0)