[英]Spring MVC Testing: Controller Method Parameters
我正在嘗試為Spring MVC Web應用程序編寫測試。
我已經成功配置了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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.