在Spring MVC Test Framework中添加要请求的用户角色

 若_时光倒影 发布于 2023-02-07 08:23

今天开始在办公室学习Spring Test MVC框架,它看起来很方便,但是直接面对一些严重的麻烦.花了几个小时谷歌搜索,但找不到与我的问题有关的任何事情.

这是我非常简单的测试类:

import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebAppContext.class)
public class ControllerTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = webAppContextSetup(wac).build();
    }

    @Test
    public void processFetchErrands() throws Exception {
        mockMvc.perform(post("/errands.do?fetchErrands=true"))
               .andExpect(status().isOk())
               .andExpect(model().attribute("errandsModel", allOf(
                   hasProperty("errandsFetched", is(true)),
                   hasProperty("showReminder", is(false)))));
    }
}

测试到达以下控制器,但if由于未正确授权,因此在第一个条款上失败.

@RequestMapping(method = RequestMethod.POST, params="fetchErrands")
public String processHaeAsioinnit(HttpSession session, HttpServletRequest request, ModelMap modelMap,
                                  @ModelAttribute(ATTR_NAME_MODEL) @Valid ErrandsModel model,
                                  BindingResult result, JopoContext ctx) {
  if (request.isUserInRole(Authority.ERRANDS.getCode())) {
    return Page.NO_AUTHORITY.getCode();
  }

  [...]
}

如何为其MockHttpServletRequest创建的用户角色添加MockMvcRequestBuilders.post(),以便我可以通过我的控制器上的权限检查?

我知道MockHttpServletRequest有一个方法addUserRole(String role),但自从MockMvcRequestBuilders.post()返回一个MockHttpServletRequestBuilder,我从来没有得到我的手MockHttpServletRequest,因此无法调用该方法.

检查Spring源代码,MockHttpServletRequestBuilder没有与用户角色相关的方法,也MockHttpServletRequest.addUserRole(String role)没有在该类中调用过,所以我不知道如何告诉它在请求中添加用户角色.

我能想到的是为过滤链添加一个自定义过滤器并HttpServletRequestWrapper从那里调用一个提供实现的自定义isUserInRole(),但对于这种情况来说这似乎有点极端.当然,框架应该提供更实用的东西吗?

1 个回答
  • 我想我找到了一种更简单的方法

    @Test
    @WithMockUser(username = "username", roles={"ADMIN"})
    public void testGetMarkupAgent() throws Exception {
    
        mockMvc.perform(get("/myurl"))
                .andExpect([...]);
    }
    

    您可能需要以下maven条目

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <version>4.0.4.RELEASE</version>
            <scope>test</scope>
        </dependency>
    

    2023-02-07 08:25 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有