今天开始在办公室学习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)))));
}
}
该测试到达以下控制器,但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()
返回a MockHttpServletRequestBuilder
,所以我从没有动手MockHttpServletRequest
,因此无法调用该方法。
检查Spring源代码,MockHttpServletRequestBuilder
没有与用户角色相关的方法,也MockHttpServletRequest.addUserRole(String role)
从未在该类中调用过,因此我不知道如何告诉它在请求中添加用户角色。
我能想到的就是在过滤器链中添加一个自定义过滤器,并HttpServletRequestWrapper
从那里调用一个提供的实现的自定义isUserInRole()
,但这在这种情况下似乎有些极端。当然,框架应该提供更实用的东西吗?
我想我找到了一种更简单的方法
@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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句