AEM MockitoJUnitRunner for servlet how to set resourceResolverFactory for AEMContext

srinivas_chann1

12-06-2020

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;

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

Accepted Solutions (1)

Accepted Solutions (1)

Veena_Vikram

MVP

16-06-2020

@srinivas_chann1 Can you try below instead of MockRequest

 

 

@Mock
private SlingHttpServletRequest req;

@Mock
private SlingHttpServletResponse res;

 

Thanks

Veena

 

Answers (1)

Answers (1)

Arun_Patidar

MVP

14-06-2020

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