Skip to content

Commit 31345a0

Browse files
committed
docs: spring mock mvc
1 parent 69289f1 commit 31345a0

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

.DS_Store

0 Bytes
Binary file not shown.

shell/.DS_Store

0 Bytes
Binary file not shown.

spring/mock_mvc_test.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
Spring Test MockMvc의 한글 깨짐
2+
3+
스프링에서 테스트 코드를 작성할 때 MockMvc를 흔히 사용한다.
4+
대략 아래와 같이 설정하고 사용한다.
5+
```java
6+
@RunWith(SpringRunner.class)
7+
@SpringBootTest
8+
public class ApiControllerTest {
9+
10+
private MockMvc mockMvc;
11+
12+
@Autowired
13+
private WebApplicationContext ctx;
14+
15+
@Before
16+
public void setup() {
17+
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx)
18+
.alwaysDo(print())
19+
.build();
20+
}
21+
22+
@Test
23+
public void 검색() throws Exception {
24+
String keyword = "sports";
25+
26+
MvcResult result = this.mockMvc
27+
.perform(
28+
get("/api/search/" + keyword)
29+
)
30+
.andExpect(status().isOk())
31+
.andReturn();
32+
}
33+
}
34+
```
35+
36+
위의 테스트 코드에서는 한글이 없으므로 아무 문제가 없는데, 아래와 같이 한글을 사용하면 깨진 한글이 Controller에 유입될 수 있으며, 결국 원하는 대로 동작하지 않게 된다.
37+
38+
```java
39+
@Test
40+
public void 검색() throws Exception {
41+
String keyword = "상품"; // 한글 사용
42+
43+
MvcResult result = this.mockMvc
44+
.perform(get("/api/search/" + keyword))
45+
.andExpect(status().isOk())
46+
.andReturn();
47+
}
48+
```
49+
50+
이 문제는 MockMvc를 설정할 때 CharacterEncodingFilter를 추가해주면 쉽게 해결할 수 있다.
51+
52+
```java
53+
@Before
54+
public void setup() {
55+
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx)
56+
.addFilters(new CharacterEncodingFilter("UTF-8", true)) // 필터 추가
57+
.alwaysDo(print())
58+
.build();
59+
}
60+
```

0 commit comments

Comments
 (0)