Spring Test :Unit Test case for successful authentication
I have authentication service, Response and Provider(Java class) which has authentication function which are responsible to get the authenticatedToken after providing the valid username/passwords and grant_type.
Below are the Service Class which method to authenticated against external authentication service.
Public interface AuthenticationService {
* @param username
* @param password
* @return
* @throws LoginAuthenticationException
*/
AuthenticationResponse authenticate(String username, String password) throws LoginAuthenticationException;
}
Below is the function inside the Response Class :
@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();}
Below is the function inside the Provider Class to authenticate :
@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;
}
}
I'm trying to write the Unit Test for all the above three Method. below are the test file I started with .. but stuck at the staring point itself :-(
Unit Test for Function inside Service class
Public class AuthenticationServiceImpl {
@InjectMocks
AuthenticationServiceImpl AuthenticationService;
@Test
public void testAuthenticate_success() throws Exception {
// ?????? Not sure how to start here?
}
}
Unit Test for Function inside Response class :
@InjectMocks
AuthenticationRepositoryImpl AuthenticationRepository;
@Test
public void testAuthenticate_success() throws Exception {
// again not sure how to start here
}
Unit Test for Function inside Provider class :
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);
??????????????????????????????????????????????????????????
}
}
I know , it's become more lengthy here but I have simple doubt how to write the unit test cases of above three file (AuthenticationService, AuthenticationResponse and AuthenticationProvider)? As a new bee to Java any suggestion and help would be appreciated :-)
java unit-testing testing junit spring-test
add a comment |
I have authentication service, Response and Provider(Java class) which has authentication function which are responsible to get the authenticatedToken after providing the valid username/passwords and grant_type.
Below are the Service Class which method to authenticated against external authentication service.
Public interface AuthenticationService {
* @param username
* @param password
* @return
* @throws LoginAuthenticationException
*/
AuthenticationResponse authenticate(String username, String password) throws LoginAuthenticationException;
}
Below is the function inside the Response Class :
@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();}
Below is the function inside the Provider Class to authenticate :
@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;
}
}
I'm trying to write the Unit Test for all the above three Method. below are the test file I started with .. but stuck at the staring point itself :-(
Unit Test for Function inside Service class
Public class AuthenticationServiceImpl {
@InjectMocks
AuthenticationServiceImpl AuthenticationService;
@Test
public void testAuthenticate_success() throws Exception {
// ?????? Not sure how to start here?
}
}
Unit Test for Function inside Response class :
@InjectMocks
AuthenticationRepositoryImpl AuthenticationRepository;
@Test
public void testAuthenticate_success() throws Exception {
// again not sure how to start here
}
Unit Test for Function inside Provider class :
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);
??????????????????????????????????????????????????????????
}
}
I know , it's become more lengthy here but I have simple doubt how to write the unit test cases of above three file (AuthenticationService, AuthenticationResponse and AuthenticationProvider)? As a new bee to Java any suggestion and help would be appreciated :-)
java unit-testing testing junit spring-test
Because of your test is not integration, why not test each class separately like "more elegant" unit test.
– borino
Nov 27 '18 at 10:38
add a comment |
I have authentication service, Response and Provider(Java class) which has authentication function which are responsible to get the authenticatedToken after providing the valid username/passwords and grant_type.
Below are the Service Class which method to authenticated against external authentication service.
Public interface AuthenticationService {
* @param username
* @param password
* @return
* @throws LoginAuthenticationException
*/
AuthenticationResponse authenticate(String username, String password) throws LoginAuthenticationException;
}
Below is the function inside the Response Class :
@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();}
Below is the function inside the Provider Class to authenticate :
@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;
}
}
I'm trying to write the Unit Test for all the above three Method. below are the test file I started with .. but stuck at the staring point itself :-(
Unit Test for Function inside Service class
Public class AuthenticationServiceImpl {
@InjectMocks
AuthenticationServiceImpl AuthenticationService;
@Test
public void testAuthenticate_success() throws Exception {
// ?????? Not sure how to start here?
}
}
Unit Test for Function inside Response class :
@InjectMocks
AuthenticationRepositoryImpl AuthenticationRepository;
@Test
public void testAuthenticate_success() throws Exception {
// again not sure how to start here
}
Unit Test for Function inside Provider class :
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);
??????????????????????????????????????????????????????????
}
}
I know , it's become more lengthy here but I have simple doubt how to write the unit test cases of above three file (AuthenticationService, AuthenticationResponse and AuthenticationProvider)? As a new bee to Java any suggestion and help would be appreciated :-)
java unit-testing testing junit spring-test
I have authentication service, Response and Provider(Java class) which has authentication function which are responsible to get the authenticatedToken after providing the valid username/passwords and grant_type.
Below are the Service Class which method to authenticated against external authentication service.
Public interface AuthenticationService {
* @param username
* @param password
* @return
* @throws LoginAuthenticationException
*/
AuthenticationResponse authenticate(String username, String password) throws LoginAuthenticationException;
}
Below is the function inside the Response Class :
@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();}
Below is the function inside the Provider Class to authenticate :
@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;
}
}
I'm trying to write the Unit Test for all the above three Method. below are the test file I started with .. but stuck at the staring point itself :-(
Unit Test for Function inside Service class
Public class AuthenticationServiceImpl {
@InjectMocks
AuthenticationServiceImpl AuthenticationService;
@Test
public void testAuthenticate_success() throws Exception {
// ?????? Not sure how to start here?
}
}
Unit Test for Function inside Response class :
@InjectMocks
AuthenticationRepositoryImpl AuthenticationRepository;
@Test
public void testAuthenticate_success() throws Exception {
// again not sure how to start here
}
Unit Test for Function inside Provider class :
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);
??????????????????????????????????????????????????????????
}
}
I know , it's become more lengthy here but I have simple doubt how to write the unit test cases of above three file (AuthenticationService, AuthenticationResponse and AuthenticationProvider)? As a new bee to Java any suggestion and help would be appreciated :-)
java unit-testing testing junit spring-test
java unit-testing testing junit spring-test
edited Nov 26 '18 at 4:05
Fatma Zaman
asked Nov 26 '18 at 3:02
Fatma ZamanFatma Zaman
196
196
Because of your test is not integration, why not test each class separately like "more elegant" unit test.
– borino
Nov 27 '18 at 10:38
add a comment |
Because of your test is not integration, why not test each class separately like "more elegant" unit test.
– borino
Nov 27 '18 at 10:38
Because of your test is not integration, why not test each class separately like "more elegant" unit test.
– borino
Nov 27 '18 at 10:38
Because of your test is not integration, why not test each class separately like "more elegant" unit test.
– borino
Nov 27 '18 at 10:38
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53474267%2fspring-test-unit-test-case-for-successful-authentication%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53474267%2fspring-test-unit-test-case-for-successful-authentication%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Because of your test is not integration, why not test each class separately like "more elegant" unit test.
– borino
Nov 27 '18 at 10:38