package com.dalab.adminservice.controller; import com.dalab.adminservice.config.TestSecurityConfiguration; import com.dalab.adminservice.dto.RoleDTO; import com.dalab.adminservice.service.IRoleService; import com.fasterxml.jackson.databind.ObjectMapper; 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.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import java.util.Collections; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.hamcrest.Matchers.hasSize; @WebMvcTest(RoleController.class) @Import(TestSecurityConfiguration.class) @WithMockUser(roles = "ADMIN") class RoleControllerTest { @Autowired private MockMvc mockMvc; @MockBean private IRoleService roleService; @Autowired private ObjectMapper objectMapper; private RoleDTO roleDTO; @BeforeEach void setUp() { roleDTO = RoleDTO.builder() .id("role-id-1") .name("VIEWER") .description("Viewer role") .build(); } @Test void getAllRealmRoles_shouldReturnListOfRoles() throws Exception { given(roleService.getAllRealmRoles()).willReturn(Collections.singletonList(roleDTO)); mockMvc.perform(get("/api/v1/admin/roles") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$[0].name").value("VIEWER")); } @Test @WithMockUser(roles = "USER") // Non-admin void getAllRealmRoles_whenUnauthorized_shouldReturnForbidden() throws Exception { mockMvc.perform(get("/api/v1/admin/roles") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); } }