我有一個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 –