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?
Solved! Go to Solution.
Views
Replies
Total Likes
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");
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");
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.
Views
Likes
Replies