Unable to Mock request in slingModel | Community
Skip to main content
November 11, 2024
Solved

Unable to Mock request in slingModel

  • November 11, 2024
  • 3 replies
  • 732 views

Hi Team,

 

Trying to mock below code in sling Model

@586265
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

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 daniel-strmecki

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

3 replies

daniel-strmecki
Community Advisor and Adobe Champion
daniel-strmeckiCommunity Advisor and Adobe ChampionAccepted solution
Community Advisor and Adobe Champion
November 11, 2024

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

Prince_Shivhare
Community Advisor
Community Advisor
November 12, 2024

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