0
I am Writing Integration test,Unable to Mock UserService. I am getting below Exception 

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“authorizationServerConfig”的bean时出错:通过字段“tokenStore”表示的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“securityConfig”的 bean 时出错:注入资源依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanNotOfRequiredTypeException:名为“userService”的 Bean 应为“org.springframework.security.core.userdetails.UserDetailsS​​ervice”类型,但实际上是“com.canco.resource.api”类型.dao.user.UserService$MockitoMock$396927620' 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:

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();
      }
     ```
4

0 回答 0