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);
}
Solved! Go to Solution.
@srinivas_chann1 Can you try below instead of MockRequest
@Mock
private SlingHttpServletRequest req;
@Mock
private SlingHttpServletResponse res;
Thanks
Veena
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);
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)
Views
Replies
Total Likes
@srinivas_chann1 Can you try below instead of MockRequest
@Mock
private SlingHttpServletRequest req;
@Mock
private SlingHttpServletResponse res;
Thanks
Veena
Views
Likes
Replies
Views
Like
Replies