Junit Test on SlingFilter | Community
Skip to main content
lokesh14
July 27, 2023
Solved

Junit Test on SlingFilter

  • July 27, 2023
  • 2 replies
  • 898 views

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.
Best answer by Nilesh_Mali

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

Nilesh_Mali
Nilesh_MaliAccepted solution
Level 3
July 27, 2023

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>); }

 

Level 2
July 28, 2023

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();