This is the test class:
@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 {}
And this is the userDetails
implementation:
@Autowired
private UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) {
User user = (User) userRepository.findByMobile(username); // user is always null
What I expect is when userRepository.findByMobile
is called, it should call the getUserByMobile
method defined in @Before
. But obviously the Mockito
config does not work OR userRepository
fail to mock. What's wrong and how to solve it?