在使用 Spring MockMVC 的 JUnit 测试中,有两种方法用于验证 Spring Security 用户的身份:@WithMockUser
使用提供的凭据创建一个虚拟用户,@WithUserDetails
获取用户名并将其解析为正确的自定义名称UserDetails
使用自定义实现UserDetailsService
(the UserDetailsServiceImpl
).
就我而言,UserDetailsService
从数据库加载用户。我要使用的用户已插入@Before
测试套件的方法。
然而,我的UserDetailsServiceImpl
找不到用户。
In my @Before
,我像这样插入用户:
User u = new User();
u.setEMail("[email protected] /cdn-cgi/l/email-protection");
u = userRepository.save(u);
并且在UserDetailsServiceImpl
:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.userRepository.findOneByEMail(username);
if (user == null)
throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
return user;
}
我如何使用在以下位置创建的帐户@Before
with @WithUserDetails
?
不幸的是,你不能轻易做到@WithUserDetails
with @Before
,因为春天@WithUserDetails
注解将在运行之前调用 Spring 安全上下文测试侦听器setUp
方法与@Before
.
Here is https://stackoverflow.com/a/38282258/1814524 https://stackoverflow.com/a/38282258/1814524一个小技巧并回答你的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)