Spring Test - 模拟@ModelAttribute

时间:2016-07-19 19:36:57

标签: java spring unit-testing spring-mvc

我有一个RestController,我试图通过Spring MVC Test进行测试。它中包含以下ModelAttribute

    @ModelAttribute("authUser")
    public User authUser(@AuthenticationPrincipal SpringAuthUser springAuthUser) throws Exception {
        User user = ConstantsHome.userprofileMgr.getUserByUserId(springAuthUser.getUsername(), true, true);
        user.updateRights(null);
        request.getSession().setAttribute(ConstantsHome.USEROBJECT_KEY, user);
        return user;
    }

当我针对此RestController运行测试时,我在NullPointerException方法中获得了authUser

有没有办法模拟这个方法,以便使用模拟方法代替这个方法进行测试?我已经阅读了其他帖子,并认为我可以在我的测试中传递“authUser”参数,但这不起作用。最终试图让这个“authUser”不要扔NPE ......这是我的测试...

    @Test
    public void testGetAllUsers() throws Exception {
        String userJson = AvadaObjectMapper.getMapper().writeValueAsString(new User());
        System.out.println("userJson=" + userJson);
        MvcResult result = this.mockMvc.perform(get("/").param("authUser", userJson).accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andDo(print())
            .andReturn();

        String content = result.getResponse().getContentAsString();

        assertTrue(content.contains("Hello"));
    }

1 个答案:

答案 0 :(得分:0)

我能够通过下面的测试配置类让我的authUser工作。特别要注意.defaultRequest...行,因为这是auth用户建立的地方。在我的所有测试中,我使用下面的类作为@ContextConfiguration类。

import com.avada.rest.api.users.UserService;
import com.avada.rest.api.users.TestUserService;
import com.avada.rest.security.SpringAuthUser;

import java.util.HashSet;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@Configuration
@ComponentScan(excludeFilters={
                @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=UserService.class)
              })
public class TestSpringRestConfig {

    public static final SpringAuthUser AUTH_USER =
        new SpringAuthUser("test", "test",
            new HashSet<GrantedAuthority>() {{
                add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }}
        );

    @Bean
    public UserService userService() {
        return new TestUserService();
    }

    @Bean
    public MockMvc mockMvc(WebApplicationContext wac) {
          return MockMvcBuilders
                 .webAppContextSetup(wac)
                 .defaultRequest(MockMvcRequestBuilders.get("/").with(SecurityMockMvcRequestPostProcessors.user(AUTH_USER)))
                 .apply(SecurityMockMvcConfigurers.springSecurity())
                 .build();
    }
}