Expand my Community achievements bar.

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

3 Replies

Avatar

Level 8

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