Junit Test on SlingFilter | Community
Skip to main content
lokesh14
New Participant
Jul 27, 2023 2:20 PM UTC
Solved

Junit Test on SlingFilter

Hi,

 

I have created a Sling filter and now I need to test it using JUnit. However, the test case is not running and is showing an error in the JUnit test.

 

The error in JUnit is pointing to the line,

MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(context.resourceResolver());

 

Kindly provide me with a solution to make the test run successfully.

 

Thanks, 

Lokesh

 

 
This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Nilesh_Mali
Nilesh_MaliAccepted solution
Level 3
Jul 27, 2023 3:47 PM UTC

Use MockSlingHttpServletRequest like below it will work 

import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest; // Add this line after Mock everything MockSlingHttpServletRequest mockRequest; @BeforeEach setup method () { request = mock(MockSlingHttpServletRequest.class); } @Test test method () { when(request.getHeader("<param>")).thenReturn(<param>); }

 

2 replies

Level 2
Jul 28, 2023 12:25 AM UTC

Hey,

You can try to create an aemContext using 

private final AemContext aemContext = new AemContext();

Using Mock annotation, initialize your request as below:

@Mock
private MockSlingHttpServletRequest request;

Then you can get the mock request using the request() method like:

request = aemContext.request();
Translate
Nilesh_Mali
Nilesh_MaliAccepted solution
Level 3
Jul 27, 2023 3:47 PM UTC

Use MockSlingHttpServletRequest like below it will work 

import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest; // Add this line after Mock everything MockSlingHttpServletRequest mockRequest; @BeforeEach setup method () { request = mock(MockSlingHttpServletRequest.class); } @Test test method () { when(request.getHeader("<param>")).thenReturn(<param>); }

 

Translate