반응형

의존성 추가

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());
    }
}
반응형

+ Recent posts