Spring Security - 无法模拟JdbcUserDetailsManager

时间:2017-10-11 07:26:17

标签: spring unit-testing spring-security mockito spring-test

我有两个用户详细信息服务。一个是JdbcUserDetailsManager,另一个是UserDetailsService我自己的客户实施。现在我需要测试它,如下所示。我无法模仿JdbcUserDetailsManager,但我可以模拟我自己的自定义实现。需要对我们的客户和我们自己的其他资源进行单独的身份验证。

它按预期工作正常,但我无法编写模拟类的测试用例。下面是我的测试课程。它抛出CannotGetJdbcConnectionException因为它正在击中真正的数据库,它已经失效。

@SpringBootTest(classes = SpringConfig.class)
@AutoConfigureMockMvc
@AutoConfigureWebMvc
@TestExecutionListeners(MockitoTestExecutionListener.class)
public class AuthenticationTest extends AbstractTestNGSpringContextTests{
    private static final String KNOWN_USER_MAIL = "valerian@mail.com";
    private static final String KNOWN_USER_PASSWORD = "pa$$w0rd";
    private static final String IN_MEMORY_KNOWN_USER_MAIL = "memuser";
    private static final String IN_MEMORY_KNOWN_USER_PASSWORD = "pass";

    @MockBean
    private AuthenticationUserService authenticationUserService;

    @MockBean
    private JdbcUserDetailsManager jdbcUserDetailsManager;

    @InjectMocks
    private DaoAuthenticationProvider daoAuthenticationProvider;

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void successLoginTest() throws Exception{
        Mockito.when(authenticationUserService.getUser(KNOWN_USER_MAIL)).thenReturn(createdTenantUser(UserAccountRole.ROLE_SUPER_ADMIN));
        Mockito.when(jdbcUserDetailsManager.loadUserByUsername(KNOWN_USER_MAIL)).thenThrow(new UsernameNotFoundException("User not found"));
        Answer<Collection<? extends GrantedAuthority>> answers = (invocationOnMock) -> getRoles();

        Mockito.when(authenticationUserService.getAuthorities(KNOWN_USER_MAIL)).thenAnswer(answers);
        ObjectMapper objectMapper = new ObjectMapper();
        JwtAuthenticationRequest loginInfo = new JwtAuthenticationRequest(KNOWN_USER_MAIL, KNOWN_USER_PASSWORD);

        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/auth")
                .content(objectMapper.writeValueAsString(loginInfo));

        mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.cookie().exists(AlSecurityConstants.AL_ACCESS_TOKEN));
    }
}

我的SpringConfig班级

@ComponentScan({"com.example.security"})
@ImportResource({"classpath:/spring-security-test.xml", "classpath:/spring-config.xml"})
@EnableWebSecurity
public class SpringConfig {

    @Bean
    @Primary
    public UserDetailsService userDetailsService() {
        return Mockito.mock(CustomUserDetailService.class);
    }

    @Bean
    public UserDetailsService jdbcManager() {
        return Mockito.mock(JdbcUserDetailsManager.class);
    }
}

我如何模仿JdbcUserDetailsManager课程?

0 个答案:

没有答案