我需要模拟JdbcDaoImpl
类来测试我的单元认证测试。我的WebSecurityConfigurerAdapter
子类配置是
@Autowired
private AnalyticsUserDetailsService userDetailsService;
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
//this configuration is for checking app resources
//this is not a regular authentication process
//it will look for user in users and authorities table in db
authenticationManagerBuilder.jdbcAuthentication().dataSource(dataSource);
}
我的测试课程:
@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;
@Autowired
private MockMvc mockMvc;
@Test
public void successLoginTest() throws Exception{
Mockito.when(authenticationUserService.getUser(KNOWN_USER_MAIL)).thenReturn(createdUser(UserAccountRole.ROLE_SUPER));
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(ACCESS_TOKEN));
}
}
如果我从我的网络安全配置类中评论configureGlobal(AuthenticationManagerBuilder auth)
方法和authenticationManagerBuilder.jdbcAuthentication().dataSource(dataSource)
,则上述测试通过。但是,如果我取消注释代码,它会抛出异常。我如何模拟JdbcDaoImpl
类,以便其loadUserByUsername(username)
方法返回预期的用户而不是命中不可用的db。我试过了@MockBean JdbcDaoImpl jdbcDaoImpl
,但它没有用。
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.