私はItem
のためのPOSTメソッドを持っています。各Itemには、作成者のUserのIDが含まれます。そして、私は使用のget著者ID用:(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
しかし、テストでは、これが結果に起因する動作しません:POSTメソッドのspring-bootテストで.getPrincipal()を実行する方法は?
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;
}
}
可能な複製(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 –