Spring boot 如何模拟UserServiceDetails和Userservice
org.springframework.beans.factory.UnsatifiedPendencyException:创建名为'authorizationServerConfig'的bean时出错:通过字段'tokenStore'表示未满足的依赖关系;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建名为“securityConfig”的bean时出错:注入资源依赖项失败;嵌套异常为org.springframework.beans.factory.beannotofrequired类型异常:名为“userService”的Bean应为“org.springframework.security.core.userdetails.UserDetailsService”类型,但实际为“com.canco.resource.api.dao.user.userService$MockitoMock$396927620” 在org.springframework.beans.factory.annotation.AutoWiredNotationBeanPostProcessor$AutoWiredFeldElement.inject(AutoWiredNotationBeanPostProcessor.java:588)~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE] 在org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]Spring boot 如何模拟UserServiceDetails和Userservice,spring-boot,spring-boot-test,spring-boot-starter-oauth2-client,Spring Boot,Spring Boot Test,Spring Boot Starter Oauth2 Client,org.springframework.beans.factory.UnsatifiedPendencyException:创建名为'authorizationServerConfig'的bean时出错:通过字段'tokenStore'表示未满足的依赖关系;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建名为“securityConfig”的bean时出错:注入资源依赖项失败;嵌套异常为org.springframew
I am Writing Integration test,Unable to Mock UserService. I am getting below Exception
服务类中的实现两个接口
````
@服务(value=“userService”)
公共类UserServiceImpl实现UserDetailsService,UserService{
私有最终记录器LOG=Logger.getLogger(getClass());
@自动连线
私有UserDAO UserDAO;
@自动连线
私有UserServiceUtil;
@自动连线
专用密码编码器;
@自动连线
私人用户;
```
对于集成测试,我尝试仅模拟UserService,无法模拟
UserControllerTest.java
```
@RunWith(SpringRunner.class)
@春靴测试
@ActiveProfiles(“测试”)
@上下文配置
@WebAppConfiguration
@AutoConfigureMockMvc()
公共类UserControllerTest{
@自动连线
私有MockMvc-MockMvc;
@自动连线
私有WebApplicationContext wac;
@自动连线
私有过滤链Proxy springSecurityFilterChain;
@自动连线
私有对象映射器对象映射器;
私有字符串serviceMsg=“serviceMsg”;
@蚕豆
私人用户服务;
私人用户管理员;
私人用户;
@以前
公共作废设置(){
mockMvc=MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity()).addFilter(springSecurityFilterChain.build();
initMocks(this);
admin=新用户();
管理员设置ID(3l);
管理员setFirstName(“John”);
管理员setLastName(“亚伯拉罕”);
管理员设置密码(“P@ss1234");
管理设置区域(“BLR”);
admin.setRole(“admin”);
管理设置状态(“活动”);
user=新用户();
user.setId(2l);
user.setFirstName(“Vinay”);
user.setLastName(“Kumar”);
user.setPassword(“P@ss1234");
user.setRegion(“SJC”);
user.setRole(“用户”);
user.setStatus(“活动”);
user.setUsername(“vinayk”);
}
@试验
public void getuserList()引发异常{
列表=新的ArrayList();
列表。添加(用户);
添加(管理员);
Page=new PageImpl(list,null,list.size());
UserService users=Mockito.mock(UserService.class);
Mockito.when(userService.getUserSummary(any(Pageable.class))),然后返回(page);
this.mockMvc.perform(get(“/api/userInfo?page=1&size=10”).header(“Authorization”、“Bearer”+obtainAccessToken(“dummyUser”、“dummyPassword”))。带有(csrf()).contentType(MediaType.APPLICATION_JSON))。
andDo(MockMvcResultHandlers.print()).andExpect(status().isOk());
}
私有字符串ActainAccessToken(字符串用户名、字符串密码)引发异常{
多值映射参数=新的LinkedMultiValueMap();
参数添加(“授权类型”、“密码”);
参数添加(“用户名”、“三部曲”);
参数添加(“密码”P@ss1234");
String credential=“clientId”+:“+”clientSecret”;
系统输出打印项次(“凭证详情”+凭证);
String base64ClientCredentials=新字符串(Base64.encodeBase64(credential.getBytes());
System.out.println(“Crednetail”+base64ClientCredentials);
结果
=mockMvc.perform(post(“/oauth/token”)
.header(“授权”、“基本”+base64ClientCredentials)
.params(params).header(“内容类型”,“应用程序/x-www-form-urlencoded”))
.andExpect(status().isOk());
字符串resultString=result.andReturn().getResponse().getContentAsString();
JacksonJsonParser=新的JacksonJsonParser();
返回jsonParser.parseMap(resultString.get(“访问令牌”).toString();
}
```
你确定你已经在测试类文件中导入了正确的UserService类。这个com.cisco.resource.api.dao.user.UserService$MockitoMock$396927620
在我看来不正确。如果我模仿,我会得到401个错误,因为模仿也适用于UserDetailsService。因为你正在为你的用户使用Spring测试上下文集成测试中,@InjectMocks
在这里没有任何意义。请务必阅读。由于您使用的是MockMvc
,您不必通过任何真实凭据,并且可以将经过身份验证的用户模拟为。@rieckpil;无论如何,我在测试中没有使用@InjectMocks。.我忘记了删除,我删除了它。
Securityconfig.java
```
Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "userService")
private UserDetailsService userDetailsService;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(authenticationEventPublisher())
.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.anonymous()
.disable()
.authorizeRequests()
.antMatchers("/api-docs/**")
.permitAll();
}
@Bean
public DefaultAuthenticationEventPublisher authenticationEventPublisher() {
return new DefaultAuthenticationEventPublisher();
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
/**
* TaskExecutor for multi threading in Spring
*
* @return
*/
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("Resource_Application");
executor.initialize();
return executor;
}
}
In Service class implements two Interfaces
````
@Service(value = "userService")
public class UserServiceImpl implements UserDetailsService, UserService {
private final Logger LOG = Logger.getLogger(getClass());
@Autowired
private UserDAO userDao;
@Autowired
private UserServiceUtil util;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private User user;
```
For the Integration test i am trying mock only UserService , Unable to Mock
UserControllerTest.java
```
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@ContextConfiguration
@WebAppConfiguration
@AutoConfigureMockMvc()
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Autowired
private ObjectMapper objectMapper;
private String serviceMsg = "serviceMsg";
@MockBean
private UserService userService;
private User admin;
private User user;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity()).addFilter(springSecurityFilterChain).build();
MockitoAnnotations.initMocks(this);
admin= new User();
admin.setId(3l);
admin.setFirstName("John");
admin.setLastName("Abraham");
admin.setPassword("P@ss1234");
admin.setRegion("BLR");
admin.setRole("Admin");
admin.setStatus("Active");
user= new User();
user.setId(2l);
user.setFirstName("Vinay");
user.setLastName("Kumar");
user.setPassword("P@ss1234");
user.setRegion("SJC");
user.setRole("User");
user.setStatus("Active");
user.setUsername("vinayk");
}
@Test
public void getuserList() throws Exception {
List<User> list = new ArrayList<User>();
list.add(user);
list.add(admin);
Page<User> page = new PageImpl<User>(list, null, list.size());
UserService users= Mockito.mock(UserService.class);
Mockito.when(userService.getUserSummary(any(Pageable.class))).thenReturn(page);
this.mockMvc.perform(get("/api/userInfo?page=1&size=10").header("Authorization", "Bearer " + obtainAccessToken("dummyUser", "dummyPassword")).with(csrf()).contentType(MediaType.APPLICATION_JSON)).
andDo(MockMvcResultHandlers.print()) .andExpect(status().isOk());
}
private String obtainAccessToken(String username, String password) throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("username", "sansubbu");
params.add("password", "P@ss1234");
String credential= "clientId"+":"+"clientSecret";
System.out.println("Crednetail" +credential);
String base64ClientCredentials = new String(Base64.encodeBase64(credential.getBytes()));
System.out.println("Crednetail" +base64ClientCredentials);
ResultActions result
= mockMvc.perform(post("/oauth/token")
.header("Authorization", "Basic " +base64ClientCredentials)
.params(params).header("Content-Type","application/x-www-form-urlencoded"))
.andExpect(status().isOk());
String resultString = result.andReturn().getResponse().getContentAsString();
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get("access_token").toString();
}
```