[英]Spring MVC Testing: Controller Method Parameters
I am trying to write tests for my Spring MVC web application. 我正在尝试为Spring MVC Web应用程序编写测试。
I have successfully configured a MockMvc
object and can execute preform()
operations, and can verify that my controller methods are being called. 我已经成功配置了MockMvc
对象,并且可以执行preform()
操作,并且可以验证是否正在调用我的控制器方法。
The issue I am experiencing has to do with passing in a UserDetails
object to my controller methods. 我遇到的问题与将UserDetails
对象传递给控制器方法有关。
My controller method signature is as follows: 我的控制器方法签名如下:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView ticketsLanding(
@AuthenticationPrincipal CustomUserDetails user) {
...
}
During the tests, user
is null (which is causing a NullPointerException
due to my code. 在测试期间, user
为null(由于我的代码,这导致NullPointerException
。
Here is my test method: 这是我的测试方法:
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"));
}
So my question is how do I properly pass a UserDetails
object into my MockMvc
controllers? 所以我的问题是如何正确地将UserDetails
对象传递到我的MockMvc
控制器中? What about other, non-security related objects such as form dtos? 其他与安全无关的对象(例如表单dto)呢?
Thanks for your help. 谢谢你的帮助。
You need to init the security context in your unit test like so: 您需要像这样在单元测试中初始化安全上下文:
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
I use the following setup: 我使用以下设置:
@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.