Expand my Community achievements bar.

SOLVED

Junit mock a HTTP Session object

Avatar

Level 3

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();
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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

View solution in original post

3 Replies

Avatar

Correct answer by
Community Advisor

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