Expand my Community achievements bar.

SOLVED

Having issue in my CommunityServletTest c

Avatar

Level 4

Dear All,

 

I have written one test class called AgenciesCommunityNodeAmangerServletTest.java for my java class AgenciesCommunityNodeAmangerServlet.java

 

when I am running my test class then I am getting below error

 

******************** TEST CLASS ERROR **********************

 

java.lang.NullPointerException
at ai.marcel.contentadmin.core.util.ApiUtility.isPublished(ApiUtility.java:1124)
at ai.marcel.contentadmin.core.servlets.AgenciesCommunityNodeAmangerServlet.doPost(AgenciesCommunityNodeAmangerServlet.java:60)
at ai.marcel.contentadmin.core.servlets.AgenciesCommunityNodeAmangerServletTest.doPostUpdateRelationShouldThrowExceptionReturn500(AgenciesCommunityNodeAmangerServletTest.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)

***************************** MY JAVA CLASS **************************

package ai.test.core.servlets;

import java.io.IOException;

import javax.servlet.Servlet;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import com.google.gson.Gson;

import ai.test.core.constants.Constants;
import ai.test.core.data.AgenciesCommunityModel;
import ai.test.core.service.ContentFragmentService;
import ai.test.core.service.EntityRelationUpdateService;
import ai.test.core.service.ServletResponse;
import ai.test.core.util.ApiUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@component(service = Servlet.class,
property = {
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths=" + "/bin/brgAgencies",
//"sling.auth.requirements=" + "-/system/sling/login"
})
public class AgenciesCommunityNodeAmangerServlet extends SlingAllMethodsServlet{


private static final long serialVersionUID = 1L;

private static final Gson gson = new Gson();

private static Logger logger = LoggerFactory.getLogger(AgenciesCommunityNodeAmangerServlet.class);

@reference
private transient ContentFragmentService contentFragmentService;

@reference
private transient EntityRelationUpdateService updateRelationService;

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException {
ApiUtility.fetchFragmentResponse(contentFragmentService, request, response, Constants.AGENCY_COMMUNITY_FRAGMENT, Constants.AGENCY, null);
}

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
String type = request.getParameter(Constants.TYPE) != null ? request.getParameter(Constants.TYPE) : "";
logger.info("type outside IF Statement !type.isEmpty() ======= " + type);
ServletResponse serviceResponse;
//AgenciesCommunityModel agenciesCommunityModel = gson.fromJson(request.getReader(),AgenciesCommunityModel.class);//coming value here
if (!type.isEmpty() && type.equals(Constants.VERIFY)) {
logger.info("type INSIDE IF Statement !type.isEmpty() ======= " + type);
boolean publishStatus = ApiUtility.isPublished(request.getResourceResolver(),request.getPathInfo());
logger.info("publishStatus INSIDE agenciesCommunity ======= " + publishStatus);
if (publishStatus == true) {
ApiUtility.verifyContentFromMDS(updateRelationService, request, response, Constants.COMMUNITIES);
}
}
else {
AgenciesCommunityModel agenciesCommunityModel = gson.fromJson(request.getReader(), AgenciesCommunityModel.class);
if(agenciesCommunityModel.getPath().equals("/"))
{
String referer = request.getHeader("Referer");
String[] parts= referer.split(".html");
if(parts.length >1)
{
String part = parts[1];
String nodePath = part.substring(0,part.lastIndexOf(Constants.SLASH));
agenciesCommunityModel.setPath(nodePath + Constants.SLASH);
}
}
serviceResponse = contentFragmentService.createNewAgenciesCommunity(agenciesCommunityModel);
ApiUtility.populateResponseObject(response, serviceResponse);
}
}
}

 

***************************** MY TEST CLASS **************************

package ai.test.core.servlets;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import javax.jcr.RepositoryException;
import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

import com.google.gson.Gson;

import ai.test.core.TestUtils;
import ai.test.core.constants.Constants;
import ai.test.core.data.AgenciesCommunityModel;
import ai.test.core.service.ContentFragmentService;
import ai.test.core.service.EntityRelationUpdateServiceImpl;
import ai.test.core.service.ServletResponse;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;

@ExtendWith({AemContextExtension.class, MockitoExtension.class})
public class AgenciesCommunityNodeAmangerServletTest {
private static final Gson gson = new Gson();

@Rule
private final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);

@Mock
ContentFragmentService agenciesService;
@Mock
ResourceResolver resourceResolver;

@Mock
SlingHttpServletRequest req;

@Mock
EntityRelationUpdateServiceImpl updateService;

@InjectMocks
private AgenciesCommunityNodeAmangerServlet agenciesCommunityNodeAmangerServlet = new AgenciesCommunityNodeAmangerServlet();

private final String COMMUNITY_PATH = "/content/dam/content-admin/global/communities/agency/test";


@BeforeEach
void setUp() throws RepositoryException, URISyntaxException {
MockitoAnnotations.initMocks(this);
context.resourceResolver();
System.out.println("resourceResolver.getUserID() ===== "+resourceResolver.getUserID());
System.out.println("resourceResolver.getAttributeNames()() ===== "+resourceResolver.getAttributeNames());
//Mockito.when(req.getResourceResolver()).thenReturn(resourceResolver);
String json = gson.toJson(TestUtils.getMockBRGCommunityModel("/content/dam/content-admin/global/communities/agency/test"));
context.request().setContent(json.getBytes());
}


@test
void doPostUpdateRelationShouldReturn200() throws IOException, LoginException {
when(updateService.updateEntityData(context.request(), COMMUNITY_PATH, Constants.COMMUNITIES)).thenReturn(TestUtils.getExpectedServletResponse(ServletResponse.ServletResponseType.RES_200));
Map<String, Object> params = new HashMap<>();
params.put(Constants.PATH, COMMUNITY_PATH);
params.put(Constants.TYPE, Constants.VERIFY);
context.request().setParameterMap(params);
agenciesCommunityNodeAmangerServlet.doPost(context.request(), context.response());

Assert.assertEquals("Response code should match", 200, context.response().getStatus());
}

@test
void doPostUpdateRelationShouldThrowExceptionReturn500() throws IOException, LoginException {
when(updateService.updateEntityData(context.request(), COMMUNITY_PATH, Constants.COMMUNITIES)).thenReturn(TestUtils.getExpectedServletResponse(ServletResponse.ServletResponseType.RES_500));
Map<String, Object> params = new HashMap<>();
params.put(Constants.PATH, COMMUNITY_PATH);
params.put(Constants.TYPE, Constants.VERIFY);
context.request().setParameterMap(params);
agenciesCommunityNodeAmangerServlet.doPost(context.request(), context.response());
Assert.assertEquals("Response code should match", 500, context.response().getStatus());
}

}

 

*********************** my APIUTILITY JAVA CLass **********************

 

public static boolean isPublished(ResourceResolver resourceResolver, String path) {
Resource resource = resourceResolver.getResource(path);
Resource jcrResource = resource.getChild(Constants.JCR_CONTENT_NODE);
if (jcrResource != null) {
return jcrResource.getValueMap().get(Constants.CQ_LAST_REPLICATION_ACTION, "")
.equalsIgnoreCase(Constants.ACTIVATE);
}
return false;
}

 

This is my first test class. Can someone please help me here.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @subnaik ,

Looking into the code, it would be very difficult to understand the exact error but I can suggest you some ways to do it -

as per the above log - on doPostUpdateRelationShouldThrowExceptionReturn500 on line number 95 which is agenciesCommunityNodeAmangerServlet.doPost(context.request(), context.response()); which is indicating this line has issue -boolean publishStatus = ApiUtility.isPublished(request.getResourceResolver(),request.getPathInfo());

 

Now I'll have to understand in line 1124, inside isPublished method which line is causing the issue. Could you please help me with what code you have in line no. 1124 of ApiUtility.java

 

Make sure you are returning some to request.getResourceResolver() and request.getPathInfo(), and accordingly, methods and objects inside inPublished.

 

I see req.getResourceResolver() but that is comment out and missing req.getPathInfo()

 

Also, you can try putting the debugger, and try to debug the code by evaluating the java objects and methods. it will be easy to navigate the issue.

 

Put a debugged on line no. 60 of your servlet, inside isPublished method and line no. 95 of your test servlet where doPost is called.

 

Let me know what output you get.

View solution in original post

2 Replies

Avatar

Correct answer by
Community Advisor

Hi @subnaik ,

Looking into the code, it would be very difficult to understand the exact error but I can suggest you some ways to do it -

as per the above log - on doPostUpdateRelationShouldThrowExceptionReturn500 on line number 95 which is agenciesCommunityNodeAmangerServlet.doPost(context.request(), context.response()); which is indicating this line has issue -boolean publishStatus = ApiUtility.isPublished(request.getResourceResolver(),request.getPathInfo());

 

Now I'll have to understand in line 1124, inside isPublished method which line is causing the issue. Could you please help me with what code you have in line no. 1124 of ApiUtility.java

 

Make sure you are returning some to request.getResourceResolver() and request.getPathInfo(), and accordingly, methods and objects inside inPublished.

 

I see req.getResourceResolver() but that is comment out and missing req.getPathInfo()

 

Also, you can try putting the debugger, and try to debug the code by evaluating the java objects and methods. it will be easy to navigate the issue.

 

Put a debugged on line no. 60 of your servlet, inside isPublished method and line no. 95 of your test servlet where doPost is called.

 

Let me know what output you get.

Avatar

Community Advisor

Hi @subnaik ,

 

You need to put a debugger point inside ApiUtility's isPublished method and inspect which object is null. NullPointerException is thrown when the application attempts to use null object, for example get operation.

 

In this case, the null object can be any of these - resourceResolver, resource ,jcrResource.getValueMap().get(Constants.CQ_LAST_REPLICATION_ACTION, "").

 

Thanks,

Ritesh Mittal