为安全控制器的集成测试设置身份验证

问题描述 投票:1回答:1

我无法为剩余控制器的集成测试设置身份验证。控制器的方法如下:

@RestController
@RequestMapping(BASE_URL)
@RequiredArgsConstructor
public class EventController {

    public static final String BASE_URL = "/api/event";

    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public void createEvent() {
        System.out.println("I am in controller");
    }
}

这是我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class EventControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;

    @BeforeEach
    public void setup() {
        mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())
            .build();
    }

    @Test
    void create() throws Exception {
        this.mockMvc.perform(post(EventController.BASE_URL)
            .with(authentication(new UsernamePasswordAuthenticationToken(
                new MyPrincipal(100, "denis"),
                null,
                Collections.singletonList(new SimpleGrantedAuthority("USER"))
            )))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"));
    }

我的测试始终由于状态为401而失败,因此我的模拟身份验证不起作用。你能告诉我如何解决吗?谢谢你的建议。

spring-boot spring-mvc spring-security spring-test spring-mvc-test
1个回答
0
投票

测试受保护请求的最简单方法是使用@WithMockUser(A_ROLE)

所以您的测试看起来像

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.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
class EventControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockUser("USER")
    void create() throws Exception {
        this.mockMvc.perform(post(EventController.BASE_URL)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json"));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.