在控制器测试中注入主体

时间:2018-02-13 07:59:12

标签: java spring mockito

我想在控制器测试中注入主要对象,但它始终为null。我已经将身份验证对象设置为SecurityContextHolder

<c:forEach var="i" begin="0" end="9">
    <h:panelGroup rendered="#{foo.size <= i}">
        <tr>
            <td class="center aligned">${foo.get(i).somethingId}</td>
            <td class="center aligned">${foo.get(i).somethingName}</td>
            <td class="center aligned">${foo.get(i).somethingDescription}</td>
        </tr>
    </h:panelGroup>
    <h:panelGroup rendered="#{foo.size > i}">
        <tr><td></td><td></td><td></td></tr>
    </h:panelGroup>
</c:forEach>

这是我之前的设置

SecurityContextHolder.getContext().setAuthentication(authentication);

但是当我打电话时

@Autowired
    private WebApplicationContext wac;

 @Before
    public void abstractControllerSetUp() {
        securityUser = getPrincipal();
        authentication = logIn();
        mockMvc = webAppContextSetup(wac).build();
    }

主体是alwyas null,它适用于app运行。

mockMvc.perform(put("/partner/notifications/activate")
                .content(toJson(command))
                .with(user(securityUser))
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());

2 个答案:

答案 0 :(得分:0)

在Spring 4.3.2中,MockMvcRequestBuilders有一个称为principal()的方法。使用它代替with(user())

mockMvc.perform(put("/partner/notifications/activate")
            .content(toJson(command))
            .principal(securityUser)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());

答案 1 :(得分:0)

尝试以下方法:

User user = new User(userName,userPassword, AuthorityUtils.createAuthorityList("YOUR_ROLES...."));
TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(user,null);

然后

mockMvc.perform(put("/partner/notifications/activate").principal(testingAuthenticationToken))