Expand my Community achievements bar.

SOLVED

Unable to Mock request in slingModel

Avatar

Level 1

Hi Team,

 

Trying to mock below code in sling Model

@inject
private SlingHttpServletRequest request;

 

Below code is in test class

private MockSlingHttpServletRequest request;

 

still request is not getting mocked and returning null value. Can you please help me on this.

 

Thanks in advance,

Ashok Vutla

1 Accepted Solution

Avatar

Correct answer by
Level 9

Hi @AshokVu,

I strongly suggest you make use of AEM Mocks library as it provides a lot of great mocks and fakes OOTB and makes testing Servets really simple. Check https://wcm.io/testing/aem-mock/usage.html

When you setup AEM Context you can do something like:

 

//initialize AEM context
MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(context.resourceResolver());
MockSlingHttpServletResponse response = new MockSlingHttpServletResponse();
request.setParameterMap(Collections.singletonMap("path", "/content/test"));
servlet.doGet(request, response);
String actualResponse = response.getOutputAsString();
//your assertions

 

 

Good luck,

Daniel

View solution in original post

3 Replies

Avatar

Correct answer by
Level 9

Hi @AshokVu,

I strongly suggest you make use of AEM Mocks library as it provides a lot of great mocks and fakes OOTB and makes testing Servets really simple. Check https://wcm.io/testing/aem-mock/usage.html

When you setup AEM Context you can do something like:

 

//initialize AEM context
MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(context.resourceResolver());
MockSlingHttpServletResponse response = new MockSlingHttpServletResponse();
request.setParameterMap(Collections.singletonMap("path", "/content/test"));
servlet.doGet(request, response);
String actualResponse = response.getOutputAsString();
//your assertions

 

 

Good luck,

Daniel

Avatar

Community Advisor

Hi @AshokVu 

Simply use Mock 

import org.mockito.Mock;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;

 

@Mock
private SlingHttpServletRequest request;
@ExtendWith(AemContextExtension.class)
class Test


Thanks