3
votes

Currently, I am having some trouble with mockito library... more exactly I am unable to inject the userRepository bean into my mocked service. For dependency injection, I am using Spring Boot. Below are some code samples:

@Service
public class UserService {

     @Autowired private TokenService tokenService;
     @Autowired private UserRepository userRepository;

     public User updateUser(User user) {
         validateUser(user); // can throw some validation errors
         createToken(user); // creates token to my user
         return userRepository.save(user);
      }
}

In my test method, I want to skip the validation and the token creation before the user gets updated.

UserService userService = mock(UserService.class);
doNothing(userService).validateUser(any());
doNothing(userService).createToken(any());

So the problem occurs in my test method when I call the updateUser method, it fails because my userRepository is not injected (NullPointerException). I tried with @Mock and @InjectMocks, but these annotations are used to inject mocks. How can I inject a real bean into my mock? Is this possible using mockito? Thank you.

2
why do u want to inject a real bean ? - user641887
In my test I need to save it into database, that's why I need the userRepository bean. - pizza.addict
How does doNothing(userService).validateUser(any()); compile? In mockito version 1.9.5 and 2.0.2 you only have a Stubber Mockito::doNothing() method - Daniele

2 Answers

1
votes

Currently you are mocking a service, which means you are replacing whole instance with mock object, even the fields. If you are interested in partial mocking (because you want to use real beans inside) you should read about spying (@Spy takes a real object, but allows to do a partial mocking).

I am not sure what are you trying to do, but my advice is to create SpringBootTest (which loads application context and creates all beans), spy on UserService bean and eventually mock behaviour of service like you are doing now.

I never tried spying beans, but I have found something: https://shekhargulati.com/2017/07/20/using-spring-boot-spybean/

0
votes

The idea of Mockito is to mock the integration points, essentially any third party calls that you make, so that you can test your unit of code. Something like , if everything else i talk to works, then my code should also work.

With that in mind, I dont think you should be using mockito for saving the entity to database. If you need to persist something in DB try writing an integration test, you can use Spring configuration to provide actual beans in that case.

Having said that, if you really need to do that, you can use ReflectionTestUtils.setField in Spring or Whitebox.setInternalState(userService, "userRepository", userRepository) for mockito.