我有身份验证服务,Response和Provider(Java类),它具有身份验证功能,负责在提供有效的用户名/密码和grant_type后获取authenticatedToken。
下面是服务类,该方法针对外部身份验证服务进行身份验证。
Public interface AuthenticationService {
* @param username
* @param password
* @return
* @throws LoginAuthenticationException
*/
AuthenticationResponse authenticate(String username, String password) throws LoginAuthenticationException;
}
下面是响应类中的函数:
@Override
public AuthenticationResponse authenticate(String username, String password) {
String AuthenticationRequest = GRANT_TYPE + DELIMITER_EQ + AuthConfig.getAuth().getGrantType()
+ DELIMITER_AMP + USERNAME + DELIMITER_EQ + username
+ DELIMITER_AMP + password + DELIMITER_EQ + password;
HttpEntity<String> request = new HttpEntity<>(AuthenticationRequest, buildHeaders(AuthConfig.getAuth().getUsername(), AuthConfig.getAuth().getPassword()));
ResponseEntity<AuthenticationResponse> response = restTemplate
.exchange(AuthConfig.getAuth().getUrl(), HttpMethod.POST, request, AuthenticationResponse.class);
return response.getBody();}
以下是 Provider类中用于进行身份验证的函数:
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
try {
AuthenticationResponse AuthenticationResponse = this.AuthenticationService.authenticate((String) authentication.getPrincipal(), (String) authentication.getCredentials());
UsernamePasswordAuthenticationToken authenticatedToken = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), null, createGrantedAuthorities(Role.ADMIN, Role.USER));
authenticatedToken.setDetails(AuthenticationResponse);
return authenticatedToken;
} catch (LoginAuthenticationException ex) {
// todo handle exceptions
LOGGER.error(Error.UNABLE_TO_AUTHENTICATE_USER.getErrorLogEvent(), ex);
throw ex;
} catch (Exception ex) {
LOGGER.error(Error.UNABLE_TO_AUTHENTICATE_USER.getErrorLogEvent(), ex);
throw ex;
}
}
我正在尝试为以上三种方法编写单元测试。下面是我开始使用..但卡在凝视点本身的测试文件:-(
服务类中的功能单元测试 公共类AuthenticationServiceImpl {
@InjectMocks
AuthenticationServiceImpl AuthenticationService;
@Test
public void testAuthenticate_success() throws Exception {
// ?????? Not sure how to start here?
}
} 响应类:
中的功能单元测试 @InjectMocks
AuthenticationRepositoryImpl AuthenticationRepository;
@Test
public void testAuthenticate_success() throws Exception {
// again not sure how to start here
}
提供者类中的功能单元测试:
import static org.junit.Assert.*;
@RunWith(MockitoJUnitRunner.class)
public class AuthenticationProviderTest {
@InjectMocks
AuthenticationProvider authenticationProvider;
@Mock
private AuthenticationService authenticationService;
@Test
public void testAuthenticate_success() throws Exception {
AuthenticationProvider test = new authenticationProvider();
assertEquals("True", authenticationProvider.authenticate(), ""Mix of number and A-Z/a-z);
assertNotNull(authenticationProvider.authenticate);
??????????????????????????????????????????????????????????
}
}
我知道,这里的时间越来越长,但是我简单地怀疑如何编写以上三个文件(AuthenticationService,AuthenticationResponse和AuthenticationProvider)的单元测试用例?作为Java的新蜂,任何建议和帮助都将不胜感激:-)