반응형
의존성 추가
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
DemoController
@RestController
public class DemoController {
@GetMapping("/api/v1/demo")
public String demoV1(@AuthenticationPrincipal UserDetails user) {
return user.getUsername();
}
}
DemoControllerTest
@AutoConfigureMockMvc
@SpringBootTest
public class DemoControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testWithoutAuthentication() throws Exception {
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/demo")
)
.andReturn();
assertEquals(HttpStatus.FOUND.value(), result.getResponse().getStatus());
}
@Test
public void testWithAuthentication() throws Exception {
UserDetails userDetails = User.builder()
.username("USERNAME")
.password("PASSWORD")
.build();
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/demo")
.with(SecurityMockMvcRequestPostProcessors.user(userDetails))
)
.andReturn();
assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
assertEquals("USERNAME", result.getResponse().getContentAsString());
}
@WithMockUser(username = "USERNAME", roles = {"USER", "ADMIN"})
@Test
public void testWithAuthenticationWithMockUser() throws Exception {
MvcResult result = mockMvc.perform(
MockMvcRequestBuilders.get("/api/v1/demo")
)
.andReturn();
assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
assertEquals("USERNAME", result.getResponse().getContentAsString());
}
}
반응형
'Development > Spring Security' 카테고리의 다른 글
[Spring Security] OAuth2 Authorization Server (0) | 2023.10.29 |
---|---|
[Spring Security] WebSocketSecurity (0) | 2023.10.29 |
[Spring Security] Jwt Authentication(Custom Filter로 직접 구현하기) (0) | 2023.10.29 |
[Spring Security] OAuth2 Authentication (0) | 2023.10.29 |
[Spring Security] Basic Authentication (0) | 2023.10.29 |