这是测试类:
@MockBean
private UserRepository userRepository;
@Before
public void beforeClass() {
String mobile;
when(this.userRepository.findByMobile(Mockito.anyString())).thenAnswer(new Answer<User>() {
@Override
public User answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return MockData.getUserByMobile((String) args[0]);
}
});
}
@Test
@WithUserDetails(value = MockData.CUSTOMER_USERNAME, userDetailsServiceBeanName = "customizedUserDetailsService")
public void testAdd() throws Exception {}
这是userDetails
实施:
@Autowired
private UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) {
User user = (User) userRepository.findByMobile(username); // user is always null
我希望在调用userRepository.findByMobile
时,它应该调用getUserByMobile
中定义的@Before
方法。但显然Mockito
配置不起作用或userRepository
无法模拟。怎么了,怎么解决?
答案 0 :(得分:2)
UserDpository用于userDetails实现,需要按照this中的描述将其注入userDetails。但是因为XXRepository在接口中,所以不能使用@InjectedMock。然后课程成为: 考试类:
@MockBean
private UserService userService;
@InjectMocks
private CustomizedUserDetailsService customizedUserDetailsService;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
when(this.userService.findByMobile(Mockito.anyString())).thenAnswer(new Answer<User>() {
@Override
public User answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return MockData.getUserByMobile((String) args[0]);
}
});
}
@Test
@WithUserDetails(value = MockData.CUSTOMER_USERNAME, userDetailsServiceBeanName = "customizedUserDetailsService") {}
userDetails:
@Autowired
private UserService userService;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) {
User user = (User) userService.findByMobile(username);
我可以看到userDetails中的userService与测试类中模拟的userService相同,但@Before
之后调用@WithUserDetails userDetails
方法。所以最后为了实现加载MockData用户,我想我必须为UT创建另一个userDetails。编辑2:实际上,我已经尝试过没有@InjectMocks并使用userService(最初我使用的是userRepository),它也可以。