0

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);
    }

}
jkfe
  • 549
  • 7
  • 29
  • 1
    1. You initialize repo mock and controller twice. 2. You don't pass the repo to the controller in the test method. – Lesiak Aug 26 '22 at 07:35
  • @Lesiak 1.Where do I initialize them twice? 2. How you propopose to do that? – jkfe Aug 26 '22 at 11:43
  • 1. Once via MockitoJUnitRunner, Mock and InjectMocks, then in test method body - by calling Mockito.mock and instantiating the controller (with new). 2. Use constructor injection in the controller - this works great both with springs DI and manual instantiation, whichever you choose. – Lesiak Aug 26 '22 at 11:55
  • 1. Good. Thanks. I removed the instantiations from the method body. 2. I did manage to inject the mock repo to the controller injecting it controller constructor. It worked indeed. I read it another way to do this would be through field instead of constructor. Do you know how that alternative works? – jkfe Aug 26 '22 at 12:07
  • InjectMocks supports field injection, if this is your question. Consult InjectMocks javadoc – Lesiak Aug 26 '22 at 12:22
  • This could provide some more details: https://stackoverflow.com/questions/74027324/why-is-my-class-not-using-my-mock-in-unit-test – knittl Oct 12 '22 at 05:54

0 Answers0