AEM cloud unit tests: how to create a SlingHttpServletRequest and set some headers? | Community
Skip to main content
Level 8
May 26, 2023
Solved

AEM cloud unit tests: how to create a SlingHttpServletRequest and set some headers?

  • May 26, 2023
  • 3 replies
  • 2371 views

Some of the service methods we use require passing in a request object, as they pull out various headers and parameters.

 

In our unit tests, we need to be able to create a request object, then set some headers on it.

 

There is the MockSligHttpServletRequest, but this cant be used as its not possible to set headers.

 

Constructor Summary

MockSlingHttpServletRequest(String resourcePath, String selectors, String extension, String suffix, String queryString)

 

This does now work:

SlingHttpServletRequest request = new SlingHttpServletRequest();  // fails because its abstract

This works, but then you cant set any headers:

import static org.mockito.Mockito.mock
:
SlingHttpServletRequest request
= mock(SlingHttpServletRequest.class);

 This works, and you can set headers, but creates a HttpRequest, not a SlingHttpServletRequest, so I cant pass it into methods expecting a SlingHttpServletRequest

HttpRequest httpRequest = new BasicHttpRequest("GET", "http://dummy.html");
httpRequest.setHeader("x-token, "testtoken");

 

Any idea how to manually create a "dummy" request with specific headers in a unit test?

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 aanchal-sikka

@tb3dock 

 

Can you please try following:

 

Using AEM Context:

var request = ctx.request();
request.setHeader("ABC", "DEF");

 

Using Mock:

var requestMock = mock(SlingHttpServletRequest.class);
when(requestMock.getHeader("ABC")).thenReturn("DEF");

 

3 replies

aanchal-sikka
Community Advisor
aanchal-sikkaCommunity AdvisorAccepted solution
Community Advisor
May 26, 2023

@tb3dock 

 

Can you please try following:

 

Using AEM Context:

var request = ctx.request();
request.setHeader("ABC", "DEF");

 

Using Mock:

var requestMock = mock(SlingHttpServletRequest.class);
when(requestMock.getHeader("ABC")).thenReturn("DEF");

 

Aanchal Sikka
ManviSharma
Adobe Employee
Adobe Employee
May 28, 2023

In Adobe Experience Manager (AEM) unit tests, you can create a "dummy" request with specific headers by using the MockSlingHttpServletRequest class and its addHeader method. Here's an example:

 

import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;

MockSlingHttpServletRequest request = new MockSlingHttpServletRequest("/path", null, null, null);
request.addHeader("headerName", "headerValue");

// Use the request object in your unit tests
myService.processRequest(request);

 

By using MockSlingHttpServletRequest and its addHeader method, you can create a request object with the desired headers and pass it to the methods you need to test.