今天在办公室开始学习Spring Test MVC Framework,看起来很顺手,但马上就遇到了一些大麻烦。花了几个小时谷歌搜索,但找不到与我的问题相关的任何内容。
这是我非常简单的测试类:
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)))));
}
}
测试到达以下 Controller ,但由于未正确授权而在第一个 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();
}
[...]
}
如何为由 MockMvcRequestBuilders.post()
创建的 MockHttpServletRequest
添加用户角色,以便我可以通过 Controller 上的权限检查?
我知道 MockHttpServletRequest
有一个方法 addUserRole(String role)
,但是由于 MockMvcRequestBuilders.post()
返回一个 MockHttpServletRequestBuilder
,我从来没有接触过 MockHttpServletRequest
,因此无法调用该方法。
检查 Spring 源代码,MockHttpServletRequestBuilder
没有与用户角色相关的方法,也没有在该类中调用过 MockHttpServletRequest.addUserRole(String role)
,所以我有不知道如何告诉它在请求中添加用户角色。
我所能想到的就是向过滤器链添加自定义过滤器并从那里调用自定义 HttpServletRequestWrapper
以提供 isUserInRole()
的实现,但这似乎是一个对于这种情况,没有什么极端的。当然,该框架应该提供更实用的东西吗?
最佳答案
我想我找到了一个 easier way
@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>
关于java - 将用户角色添加到 Spring MVC 测试框架中的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20884399/