How to set role in MockHttpServletRequest?

2019-09-09 09:56发布

问题:

I have read following topic:

https://stackoverflow.com/a/18487953/2674303

But it is a bit not my variant.

Inside my method controller which I need to test I have following line:

httpServletRequest.isUserInRole("ROLE_OWNER");

How can I set role in MockHttpServletRequest ?

回答1:

 mockMvc.perform(post("/owner/terminals/edit").principal(principal).with(new RequestPostProcessor() {
            public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
                request.addUserRole("ROLE_OWNER");
                return request;
            }