Spring MVC Test with RequestPostProcessor vs. Anno

2019-05-10 08:54发布

I have an application I've created with JHipster. I generated a Blog entity, then modified the BlogResource class so its getAll() method only returns the blog for the current user.

/**
 * GET  /blogs -> get all the blogs.
 */
@RequestMapping(value = "/blogs",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Blog> getAll() {
    log.debug("REST request to get all Blogs");
    return blogRepository.findAllForCurrentUser();
}

BlogRepository has the following for its findAllForCurrentUser() method.

@Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
List<Blog> findAllForCurrentUser();

To test this, I was able to use Spring Security's RequestPostProcessor:

@Test
@Transactional
public void getAllBlogs() throws Exception {
    restBlogMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();

    // Initialize the database
    blog.setUser(userRepository.findOneByLogin("user").get());
    blogRepository.saveAndFlush(blog);

    // Get all the blogs
    restBlogMockMvc.perform(get("/api/blogs").with(user("user")))
        //.andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.[*].id").value(hasItem(blog.getId().intValue())))
        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
        .andExpect(jsonPath("$.[*].handle").value(hasItem(DEFAULT_HANDLE.toString())));
}

I'm curious to know why using annotations like @WithMockUser and @WithUserDetails won't work for this. If I change it to use annotations, I get the following error:

[DEBUG] org.jhipster.app.security.Http401UnauthorizedEntryPoint - Pre-authenticated entry point called. Rejecting access

java.lang.AssertionError: Status 
Expected :200
Actual   :401

0条回答
登录 后发表回答