I have a POST method which for sends Item
. Each Item contains the id of User which author. And for get author id I use :(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
But in test, this does not work due to result :
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 method:
@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";
}
And test:
@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);
}
Why ClassCastException
does not throw then I send data from the browser form? How fix this issue?
Thank You.
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;
}
}