Reputation: 163
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.
Upvotes: 4
Views: 14241
Reputation: 11822
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:
when
on an object that isn't even a mock, and/oryou 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
Upvotes: 4