Reputation: 93
I have written the controller test. However I am not able to pass the test. Is there anything wrong with the way I have written the test or the service method?
@Test
void controller_getUserTest() throws Exception {
UserEntity user = getUser(); //dummy user from getUser() helper method
when(userService.getUser("jeremy")).thenReturn(user);
this.mockMvc.perform(get("/user/jeremy")).andDo(print())
.andExpect(status().isOk());
}
@GetMapping("/{username}")
public ResponseEntity<UserEntity> getUser(@PathVariable String username) {
System.out.println(username);
UserEntity theUser = userService.getUser(username);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
if(theUser == null) {
String errorMessage = "User Not Found";
return new ResponseEntity(errorMessage,headers,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<UserEntity>(theUser,headers,HttpStatus.OK);
}
@Override
@Transactional
public UserEntity getUser(String username) {
UserEntity probe = new UserEntity();
probe.setUsername(username);
probe.setEnabled(true);
ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreCase();
Example<UserEntity> example = Example.of(probe,matcher);
Optional<UserEntity> result = userRepository.findOne(example);
return result.isPresent()? result.get() : null;
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
UserEntity cannot be returned by findOne()
findOne() should return Optional
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
I also have a getUser() method defined to init a dummy user for tests
Edit:
I realised that I wasnt using a mock instance of the UserService class, however, when I tried to use one, the error still appear.
Upvotes: 2
Views: 433
Reputation: 93
I realised that the UserService instance I was using is an actual service instance instead of a mocked one, thats why it failed the test.
Upvotes: 1