Skip to main content
Level 3
May 15, 2023
Solved

Junit mock a HTTP Session object

  • May 15, 2023
  • 2 replies
  • 2190 views

Hello,

 

We have a requirement where we need to set some attributes to the session object through out the user journey and finally, we need to read the session attribute names and will read each attribute name. 

Can someone suggest how I can mock these values:

 

Here is the sample code:

Fields fields= new Fields();
if (session != null) {
Enumeration<String> attributeNames = session.getAttributeNames();
List<FieldItems> positiveList = new ArrayList<>();
List<FieldItems> negativeList = new ArrayList<>();


while (attributeNames.hasMoreElements()) {

String attributeName = attributeNames.nextElement();
if (attributeName.startsWith(PAGE_PATH)) {
String attributeValue = session.getAttribute(attributeName).toString();
This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by ShubhanshuSi2

Initialize AemContext object

private final AemContext context = new AemContext();


Get SlingHttpServletRequest object from context

SlingHttpServletRequest request = context.request(); request.getSession().setAttribute("key", "value");



 For additional information refer official documentation here: Usage | wcm.io

2 replies

Level 3
May 15, 2023
ShubhanshuSi2Community AdvisorAccepted solution
Community Advisor
May 15, 2023

Initialize AemContext object

private final AemContext context = new AemContext();


Get SlingHttpServletRequest object from context

SlingHttpServletRequest request = context.request(); request.getSession().setAttribute("key", "value");



 For additional information refer official documentation here: Usage | wcm.io

Level 3
May 15, 2023

@shubhanshusi2 It works. Thanks for swift response.