Java SpringMVC测试:控制器方法参数
我正在尝试为我的SpringMVCWeb应用程序编写测试 我已成功配置了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
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();
}
}