Expand my Community achievements bar.

SOLVED

AEM MockitoJUnitRunner for servlet how to set resourceResolverFactory for AEMContext

Avatar

Level 8

Hi,

 

Could some one provide inputs on the below

 

code in servlet is giving null exception for resourceResolverFactory .how to mock that using aemContext

 

Servelt class

 

public void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response){

@reference
private ResourceResolverFactory resourceResolverFactory;

@Override
public void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException, IOException {
....
...
Map<String, Object> subService = new HashMap<>();
subService.put(ResourceResolverFactory.SUBSERVICE, SUB_SERVICE);
resourceResolver = resourceResolverFactory.getServiceResourceResolver(subService);
session = resourceResolver.adaptTo(Session.class);
......

response.setContentType(APPLICATION_JSON_UTF8);
}

 

 

In test class:-

@RunWith(MockitoJUnitRunner.class)
public class MyServletTest {

@InjectMocks
private MyServlet servlet;

@Deleted Account
public final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);

@Mock
private MockSlingHttpServletRequest req;

@Mock
private MockSlingHttpServletResponse res;

 

@Before
public void init() throws Exception {
servlet = new MyServlet();
req = context.request();
res = context.response();

}

@test
public void doGet_shouldReturnHeaderAsExpected() throws IOException, ServletException {
servletUnderTest.doGet(req, res);
assertEquals(res.getContentType(), APPLICATION_JSON_UTF8);
}

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@srinivas_chann1 Can you try below instead of MockRequest

 

 

@Mock
private SlingHttpServletRequest req;

@Mock
private SlingHttpServletResponse res;

 

Thanks

Veena

 

View solution in original post

3 Replies

Avatar

Community Advisor

Check https://wcm.io/testing/aem-mock/usage.html#Registering_OSGi_service

Try to inject service in init method 

 

// prepare sling request
MockResourceResolverFactory resourceResolverFactory = new MockResourceResolverFactory();
ResourceResolver resolver = resourceResolverFactory.getResourceResolver(null);
MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resolver);

 



Arun Patidar

Avatar

Level 8

Thanks for inputs.

It showing an error in IDE  for line MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resolver);

 

That

 

MockSlingHttpServletRequest (org.osgi.framework.BundleContext) in MockSlingHttpServletRequest cannot be applied to (ResourceResolver)

Avatar

Correct answer by
Community Advisor

@srinivas_chann1 Can you try below instead of MockRequest

 

 

@Mock
private SlingHttpServletRequest req;

@Mock
private SlingHttpServletResponse res;

 

Thanks

Veena