File size: 2,440 Bytes
d6afd6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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());
    }
}