JAVA 單元測試 初探

最近在學習JAVA的單元測試(UNIT TEST)
具體會用到的package有這些

1
2
3
4
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.7.2'

要入門的方式最好是從測試API開始
所以我寫了一個health check return 200

1
2
3
4
5
6
7
8
@RestController
@RequestMapping("/")
public class L7HealthCheck {
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> healthCheck() {
return new ResponseEntity<>("OK", HttpStatus.OK);
}
}

接下來要寫的是Test Function

首先先寫好前置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
@EnableWebMvc
public class SimpleControllerTest {

@Autowired private WebApplicationContext ctx;
private MockMvc mockMvc;

@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}

@Configuration
public static class TestConfiguration {
@Bean public L7HealthCheck l7HealthCheck () {
return new L7HealthCheck();
}
}
}

中間再加上最主要的test function

1
2
3
4
5
6
7
@Test public void testL7healthCheck() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_PLAIN))
.andDo(print()) // print the request/response in the console
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.TEXT_PLAIN))
.andExpect(content().string("OK"));
}

最後run這個task ~~

然後就失敗了!!! WHY!!!?
看一下log…
Imgur
原來是Response編碼不合的問題

上網查找一下
看到StackOverflow有人給出這樣的答案

1
2
3
4
5
6
7
8
9
MediaType MEDIA_TYPE_JSON_UTF8 = new MediaType("application", "json", java.nio.charset.Charset.forName("UTF-8"));
MockHttpServletRequestBuilder request = post("/myPostPath");
request.content(json);
request.locale(Locale.JAPANESE);
request.accept(MEDIA_TYPE_JSON_UTF8);
request.contentType(MEDIA_TYPE_JSON_UTF8);
mockMvc.perform(request)
.andDo(print())
.andExpect(status().isOk());

標準的MediaType裡面沒有這種編碼,自己做一個不就得了?
於是加入一行

1
2
3
4
5
6
7
8
9
MediaType MEDIA_TYPE_ISO8859 = new MediaType("application", "json", java.nio.charset.Charset.forName("ISO-8859-1"));

@Test public void testL7healthCheck() throws Exception {
mockMvc.perform(get("/").accept(MEDIA_TYPE_ISO8859))
.andDo(print()) // print the request/response in the console
.andExpect(status().isOk())
.andExpect(content().contentType(MEDIA_TYPE_ISO8859))
.andExpect(content().string("OK"));
}

PASSED~!
完美解決 <3

REF

StackOverflow: