Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito and Java Spring - repository in tests

I am new to mockito / Java Spring and I tried to make a test. I have an admin controller, with this method in it :

@RequestMapping(value="/admin/users", method = RequestMethod.GET)
public ResponseEntity<List<User>>users(){
    List<User> students=this.userService.getAll();
    if(students.isEmpty())
        return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
    return  new ResponseEntity<List<User>>(students,HttpStatus.OK);
}

Now, I tried to make a test, to see if it works, something like this :

public class AdminControllerTest {

    @InjectMocks
    private AdminController controller;

    @InjectMocks
    private UserServiceImpl userService = new UserServiceImpl();

    @Mock
    private UserRepository userRepository;

    private MockMvc mockMvc;

    @Before
    public void setup(){

        MockitoAnnotations.initMocks(this);

        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void test() throws Exception {

        User user = new User();
        user.setId(5);
        user.setActive(true);
        user.setLastName("Test1");
        user.setName("Test1");
        user.setPassword("123123");
        user.setRole(User.Role.student);
        user.setEmail("[email protected]");
        when(userService.save(user)).thenReturn(user);
        userService.save(user);
        mockMvc.perform(get("/admin/users")).andDo(print());

    }

}

The problem is that I am not sure how to make the Test class add items to the repository. I tried it this way but I get NullPointerExceptions. I am guessing it is because the repository is empty and when the .getAll() method is called it returns the error.

like image 253
Gimv13 Avatar asked Sep 06 '25 03:09

Gimv13


1 Answers

Since you've mocked out the repository, you don't need to save things to it. All you need to do is specify what the repository would return when certain methods are called.

Instead of:

when(userService.save(user)).thenReturn(user);

... try using:

when(userRepository.findAll()).thenReturn(Collections.singletonList(user));

Why it didn't work

The reason you were getting NullPointerException was one of:

  1. you are setting up a when on an object that isn't even a mock, and/or
  2. you didn't provide a when for the userRepository.findAll() method, so it returned null when you called it:

    List<User> students=this.userService.getAll(); <-- returned null
    

    ... which was then dereferenced and threw the NPE:

    if(students.isEmpty()) <-- throws NPE when students is null
    
like image 160
Jason Avatar answered Sep 07 '25 22:09

Jason