Expand my Community achievements bar.

July 31st AEM Gems Webinar: Elevate your AEM development to master the integration of private GitHub repositories within AEM Cloud Manager.
SOLVED

Junit Test on SlingFilter

Avatar

Level 1

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

 

 
1 Accepted Solution

Avatar

Correct answer by
Level 3

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

 

View solution in original post

2 Replies

Avatar

Correct answer by
Level 3

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

 

Avatar

Level 2

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