今天开始在办公室学习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()
,但对于这种情况来说这似乎有点极端.当然,框架应该提供更实用的东西吗?
我想我找到了一种更简单的方法
@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>