我想在 Controller 测试中注入(inject)主体对象,但它始终为空。我已经将身份验证对象设置为 SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(authentication);
这是我之前的设置
@Autowired
private WebApplicationContext wac;
@Before
public void abstractControllerSetUp() {
securityUser = getPrincipal();
authentication = logIn();
mockMvc = webAppContextSetup(wac).build();
}
但是当我调用
mockMvc.perform(put("/partner/notifications/activate")
.content(toJson(command))
.with(user(securityUser))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
principal 始终为 null,它在应用程序运行时起作用。
@PutMapping("/activate")
public void activateNotification(@RequestBody NotificationCommand command, @AuthenticationPrincipal Principal principal) {
最佳答案
在 Spring 4.3.2 中,MockMvcRequestBuilders
有一个名为 principal()
的方法。使用它代替 with(user())
。
mockMvc.perform(put("/partner/notifications/activate")
.content(toJson(command))
.principal(securityUser)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
关于java - 在 Controller 测试中注入(inject)主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48762000/