• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to write a JUnit test for Spring COntroller which deals with Authentication  RSS feed

ravi tej
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Below is the sample code of My Controller. I need to write a JUnit test method for the below method "getNextVersionBySessionKey."

public class PublicationController extends AbstractController {

@RequestMapping(value = "Publication/Get/NextVersion/BySessionKey/")
public @ResponseBody

ReturnStatus<String> getNextVersionBySessionKey()
throws ContentStandardSecurityException, ContentStandardException,
DaoException {
String sessionKey = (new UserInformation()).getSessionKey();
ReturnStatus<String> status = new ReturnStatus<String>(
return status;


The above method calls the "UserInformation" method to retrieve the session key. Below is the code of the class "UserInformation"

public class UserInformation {

private Authentication mAuthenticationInformation = null;

public UserInformation() {
mAuthenticationInformation = getAuthentication();

public String getSessionKey() throws ContentStandardSecurityException{
CoreStamdardsLoginModule.UsernamePrincipal authenticatedPrincipal = null;
try {
for (GrantedAuthority authority : mAuthenticationInformation
.getAuthorities()) {
// we are only using the first principal.
JaasGrantedAuthority jaasAuthority = (JaasGrantedAuthority) authority;
authenticatedPrincipal = (CoreStamdardsLoginModule.UsernamePrincipal) jaasAuthority
} catch (Exception exp) {
throw new ContentStandardSecurityException(exp.getMessage());
return authenticatedPrincipal.getSessionKey();

private Authentication getAuthentication() {

StringBuilder builder = new StringBuilder("");
Subject subject = Subject.getSubject(AccessController.getContext());
if (subject != null) {
+ " is....: " + subject);

Authentication auth = SecurityContextHolder.getContext()
if (auth != null) {

builder.append("Authentication object is of type: <em>"
+ auth.getClass().getName() + "</em>");
builder.append("Authentication object as a String: <br/><br/>"
+ auth.toString());

builder.append("Authentication object holds the following granted authorities:<br /><br />");
for (GrantedAuthority authority : auth.getAuthorities()) {
builder.append(authority + "(<em>" + authority.getAuthority()
+ "</em>:" + authority.getAuthority() + "<br />");

builder.append("<p><b>Success! Your web filters appear to be properly configured!</b></p>");
} else {
builder.append("Authentication object is null.<br />");
builder.append("This is an error and your Spring Security application will not operate properly until corrected.<br /><br />");

return auth;

Could any one please guide in writing the JUnit for this controller.

Thanks in Advance.

Ravi Teja
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!