如何仅使用Mockito在Spring中模拟bean的方法? [英] How to only mock a method of a bean in Spring using Mockito?
本文介绍了如何仅使用Mockito在Spring中模拟bean的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Spring测试中,我使用@Primary
和@Profile
来模拟一个bean:
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;
}
但是UserService
bean的其他方法返回null
,我怎么能监视真正创建的bean而仅模拟tokenValidation
方法?
But other methods of UserService
bean return null
, how can i spy the real created bean and only mock tokenValidation
method?
推荐答案
要侦察UserService
bean的一种方法,在构造该bean的过程中,我们通过将其作为参数发送并通过Spring上下文自动连接UserService的现有实例,并使用Mockito的间谍程序功能:
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;
}
这篇关于如何仅使用Mockito在Spring中模拟bean的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文