Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject beans into mocks created with mockito

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.

like image 351
pizza.addict Avatar asked Oct 18 '25 11:10

pizza.addict


1 Answers

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/

like image 61
staszko032 Avatar answered Oct 21 '25 01:10

staszko032



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!