I use @Primary
and @Profile
to mock a bean in Spring test:
@Profile("test")
@Configuration
public class TestBeanConf {
@Bean
@Primary
public UserService userService() {
UserService userService = Mockito.mock(UserService.class);
TokenValidationUrl validation = new TokenValidationUrl();
validation.setValid(true);
validation.setUid("123456789");
Mockito.when(userService.tokenValidation("23456")).thenReturn(validation);
return userService;
}
But other methods of UserService
bean return null
, how can i spy the real created bean and only mock tokenValidation
method?
To spy one method of UserService
bean, during construction of this bean we autowire existing instance of UserService from Spring context by sending it as paramter and use Mockito's spying feature:
@Profile("test")
@Configuration
public class TestBeanConf {
@Bean
@Primary
public UserService userServiceTest(UserService userService) {
UserService userService = Mockito.spy(userService);
TokenValidationUrl validation = new TokenValidationUrl();
validation.setValid(true);
validation.setUid("123456789");
Mockito.when(userService.tokenValidation("23456")).thenReturn(validation);
return userService;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.