I'm writing a unit test to test the addUser method of a @RestController class.
But when the following line is executed:
ResponseEntity<?> validUser = userController.addUser(userDTO);
It returns this error:
<400 BAD_REQUEST Bad Request,An error occurred: Cannot invoke "UserRepository.save(Object)" because "this.userRepository" is null,{}>
@RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserController userController;
private UserDTO userDTO;
private UserDTO invalidUserDTO;
@BeforeEach
void setup() {
}
@Test
public void testAddUserIsValid() {
userDTO = new UserDTO();
// fill userDTO data
User user = new User();
// fill user data
userRepository = mock(UserRepository.class);
when(userRepository.save(any(User.class))).thenReturn(user);
userController = new UserController();
ResponseEntity<?> validUser = userController.addUser(userDTO);
assertTrue(validUser.getBody() instanceof UserDTO);
}
}