I am working on my first spring boot project and I am having trouble with testing my class as a Mockito newbie. I need to check that the findAndUpdateUser method below update User entity fields correctly :
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepo;
public User findUser(String id) {
return userRepo.findById(id);
}
public User findAndUpdateUser(String id) {
User foundUser = findUser(id);
//some update on foundUser fields
return foundUser;
}
}
To test, I need to mock entity bean because I don't have DB locally. Here is my test class :
@RunWith(MockitoJUnitRunner.class)
public class UpdateFieldsTest {
@Mock
private UserRepository userRepo;
@Test
public void test1() {
User user = new User();
user.setId("testId");
//setting some other user fields
Mockito.when(userRepo.findById("testId")).thenReturn(user);
UserServiceImpl userService = new userServiceImpl();
User returnedUser = userService.findAndUpdateUser("testId");
//Checking if user field values are updated after findAndUpdate call
Assert.xxx
//other asserts
}
}
But this code throw me some NullPointerException on method call. I even tried to mock findUser method but I still have error...
Am I having a bad approach ? How should I test my method ?
Any help is welcomed Thanks all