jndp
jndp

Reputation: 93

Mockito Test failed with when/thenReturn

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?

  1. This is the test I'm running:
        @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());
        }
  1. This is the controller method that I'm testing:
@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);
    }
  1. This is the service method that was being mocked in when():
    @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;
  1. The error message when the test failed:
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

Answers (1)

jndp
jndp

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

Related Questions