Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringMVC测试:控制器方法参数_Java_Spring_Spring Mvc_Spring Test Mvc - Fatal编程技术网

Java SpringMVC测试:控制器方法参数

Java SpringMVC测试:控制器方法参数,java,spring,spring-mvc,spring-test-mvc,Java,Spring,Spring Mvc,Spring Test Mvc,我正在尝试为我的SpringMVCWeb应用程序编写测试 我已成功配置了MockMvc对象,可以执行preform()操作,并可以验证是否正在调用我的控制器方法 我遇到的问题与将UserDetails对象传递给我的控制器方法有关 我的控制器方法签名如下: @RequestMapping(method = RequestMethod.GET) public ModelAndView ticketsLanding( @AuthenticationPrincipal CustomUse

我正在尝试为我的SpringMVCWeb应用程序编写测试

我已成功配置了
MockMvc
对象,可以执行
preform()
操作,并可以验证是否正在调用我的控制器方法

我遇到的问题与将
UserDetails
对象传递给我的控制器方法有关

我的控制器方法签名如下:

@RequestMapping(method = RequestMethod.GET)
public ModelAndView ticketsLanding(
        @AuthenticationPrincipal CustomUserDetails user) {
    ...
}
在测试过程中,
user
为null(这导致了由于我的代码而产生的
NullPointerException

以下是我的测试方法:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;

@Test
public void ticketsLanding() throws Exception {
    // testUser is populated in the @Before method
    this.mockMvc.perform(
            get("/tickets").with(user(testUser))).andExpect(
            model().attributeExists("tickets"));
}
因此,我的问题是如何将
UserDetails
对象正确地传递到我的
MockMvc
控制器中?其他与安全无关的对象(如表单DTO)呢


感谢您的帮助。

您需要在单元测试中初始化安全上下文,如下所示:

@Before
public void setup() {
    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) 
            .build();
}

我使用以下设置:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { 
        "classpath:/spring/root-test-context.xml"})
public class UserAppTest implements InitializingBean{

    @Autowired
    WebApplicationContext wac;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    // other test methods...

    @Override
    public void afterPropertiesSet() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac)
                .addFilters(springSecurityFilterChain)
                .build();
    }
}