import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class RestControllerExceptionAdviceTest {
@BeforeEach
void init(WebApplicationContext ctx){
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx)
.addFilters(new CharacterEncodingFilter("UTF-8", true))
.build();
}
private MockMvc mockMvc;
@Test
void legacy_not_filtered() throws Exception {
mockMvc.perform(get("/legacy/greeting"))
.andExpect(status().isOk())
.andExpect(content().string("{\"msg\":\"hello, legacy controller\"}"))
.andDo(print());
}
@Test
void no_authorization_header() throws Exception {
mockMvc.perform(get("/rest/greeting"))
.andDo(print())
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code", equalTo("UNAUTHORIZED")))
;
}
@Test
void wrong_authorization_header1() throws Exception {
mockMvc.perform(
get("/rest/greeting")
.header("Authorization", "bearer abc")
)
.andDo(print())
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code", equalTo("UNAUTHORIZED")))
;
}
@Test
void wrong_authorization_header2() throws Exception {
mockMvc.perform(
get("/rest/greeting")
.header("Authorization", "Bearer abc")
)
.andDo(print())
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.code", equalTo("ACCESS_TOKEN_ERROR")))
.andExpect(jsonPath("$.message", containsString("유효하지 않은")))
;
}
}