我有一个POST方法,用于发送Item
。每个项目包含作者的用户的ID。而对于GET作者ID我用:(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
但在测试中,这不起作用由于导致:如何.getPrincipal()在POST方法的spring-boot测试?
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to ru.pravvich.domain.User
POST方法:
@PostMapping("/get_all_items/add_item_page/add_item")
public String addItem(@RequestParam(value = "description") final String description) {
final User user = (User) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
final Item item = new Item();
item.setDescription(description);
item.setAuthorId(user.getId());
service.add(item);
return "redirect:/get_all_items";
}
和测试:
@Test
@WithMockUser(username = "user", roles = "USER")
public void whenPostThenAdd() throws Exception {
Item item = new Item();
item.setDescription("test");
mvc.perform(
post("/get_all_items/add_item_page/add_item")
.param("description", "test")
).andExpect(
status().is3xxRedirection()
);
verify(itemService, times(1)).add(item);
}
为什么ClassCastException
不会抛出然后我从浏览器窗体发送数据?如何解决这个问题?
谢谢。
UPDATE:
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
if (user == null) user = new User();
return user;
}
}
的[为什么春天测试失败,不能正常工作@MockBean]可能的复制(https://stackoverflow.com/questions/45905591/why-spring-test-is-fail-does-not -work-mockbean) –
你有可能使用'@ WithUserDetails'? https://docs.spring.io/spring-security/site/docs/current/reference/html/test-method.html#test-method-withuserdetails –