how to do servlet unit testing | Community
Skip to main content
naveent23995593
Level 3
April 27, 2018
Solved

how to do servlet unit testing

  • April 27, 2018
  • 50 replies
  • 19495 views

hi guys i need help from you, i created chillist servlet for reading properties from /content it returns a JSONArray of the node's child node paths and properties.

so plz help for unit testing. i need unit testing script for this code, this my code

package com.aem.community.core.servlets;

import java.io.IOException;

import javax.jcr.Node;

import javax.jcr.NodeIterator;

import javax.jcr.RepositoryException;

import javax.servlet.ServletException;

import org.apache.felix.scr.annotations.Service;

import org.apache.felix.scr.annotations.sling.SlingServlet;

import org.apache.sling.api.SlingHttpServletRequest;

import org.apache.sling.api.SlingHttpServletResponse;

import org.apache.sling.api.resource.Resource;

import org.apache.sling.api.resource.ResourceResolver;

import org.apache.sling.api.servlets.SlingAllMethodsServlet;

import org.apache.sling.commons.json.JSONArray;

import org.apache.sling.commons.json.JSONException;

import org.apache.sling.commons.json.JSONObject;

import org.apache.sling.commons.json.jcr.JsonJcrNode;

import org.osgi.service.component.annotations.Component;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

@Component(enabled = true, immediate = true)

@Service(ChildList.class)

@SlingServlet(resourceTypes="sling/servlet/default",selectors="childlist",methods="GET",extensions="json",metatype=true)

public class ChildList extends SlingAllMethodsServlet {

protected final Logger loger = LoggerFactory.getLogger(ChildList.class);

private static final long serialVersionUID = 9176255033916949528L;

private JSONArray array;

@Override

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

throws ServletException, IOException {

try{

ResourceResolver resolver = request.getResourceResolver();

Resource resource = resolver.getResource(request.getRequestPathInfo().getResourcePath());

Node node = null;

if (resource != null) {

node = resource.adaptTo(Node.class);

}

if (node == null){

throw new RepositoryException();

}

NodeIterator it = node.getNodes();

array = new JSONArray();

while (it.hasNext()) {

Node child = it.nextNode();

if (loger.isDebugEnabled()){

loger.debug("resource......."+child.getPath());

}

JSONObject obj = new JsonJcrNode(child);

array.put(obj);

response.setContentType("application/json");

response.getOutputStream().print(array.toString());

}

}

catch(RepositoryException e) {

throw new ServletException("404 HTTP ERROR Page Not Found", e);

}

catch(JSONException e)

{

loger.error("Could not formulate JSON response");

throw new ServletException("Error", e);

}

}

}

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by joerghoh

Today I rewrote unittests for the whole day ... so while I just was on it, I wrote them for this question, too.

You can find the complete code at https://github.com/joerghoh/cqdump/tree/master/unittests

Clone it and then run it (the usual "mvn clean install").

The relevant bits and pieces:

I used the AEM Mocks from wcm.io, which work pretty good for usecases like yours.

HTH,

Jörg

50 replies

smacdonald2008
Level 10
May 2, 2018

You should still be able to invoke it using Java HTTP API and use an asset call to test return value.

Daniel_Gordon
Adobe Employee
Adobe Employee
May 2, 2018

I'd look into using Sling Mocks or other mocking frameworks to simulate complex objects that are impractical to incorporate into the unit test. The goal should be to isolate and test behavior of the code within the servlet, not necessarily the servlet itself. Check out Sling Mocks: Apache Sling :: Sling Mocks . Mocks can be used to unit test code prior to deployment.

If you do want to some more real-world testing (on say a stage/QA environment) you can also look into server side integration testing as well: https://sling.apache.org/documentation/development/sling-testing-tools.htm (Maven achetype 13 has an example of server-side integration test). These will be executed after code is deployed to the AEM environment.

naveent23995593
Level 3
May 2, 2018

if u dnt mind.., execute my code in ur ide, and write unittest for our code,and send me

plz guys this is my 1st time usnit testing i dnt know how run how to write in aem

joerghoh
Adobe Employee
joerghohAdobe EmployeeAccepted solution
Adobe Employee
May 2, 2018

Today I rewrote unittests for the whole day ... so while I just was on it, I wrote them for this question, too.

You can find the complete code at https://github.com/joerghoh/cqdump/tree/master/unittests

Clone it and then run it (the usual "mvn clean install").

The relevant bits and pieces:

I used the AEM Mocks from wcm.io, which work pretty good for usecases like yours.

HTH,

Jörg

naveent23995593
Level 3
May 3, 2018

yeah thank you Jörg Hoh

naveent23995593
Level 3
May 3, 2018

i did't get it..https://github.com/joerghoh/cqdump/blob/master/unittests/core/src/main/java/de/joerghoh/cqdump/core/servlets/ChildListOptimized.java   why it is using ChildListOptimized.java..,

private JSONObject convertResourceToJSON (Resource resource) throws JSONException {

JSONObject obj = new JSONObject();

obj.put("jcr:path", resource.getPath());

ValueMap vm = resource.adaptTo(ValueMap.class);

vm.forEach((key,value) -> {

vm.put(key, value);

});

return obj;

}

*  in that what is key and value it's getting error

joerghoh
Adobe Employee
Adobe Employee
May 3, 2018

You can safely ignore the "optimized version" for the moment; I just wanted to demonstrate that you can easily achieve the (more or less) same functionality without using the JCR API.

Jörg

naveent23995593
Level 3
May 3, 2018

mvn clean install

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.2:testCompile (default-testCompile) on project aandes.core: Compilation failure

[ERROR] /C:/Users/Naveen/aandes/core/src/test/java/com/aem/community/core/models/ChildListTest.java:[49,24] cannot access org.junit.rules.TestRule

[ERROR] class file for org.junit.rules.TestRule not found

[ERROR] -> [Help 1]

joerghoh
Adobe Employee
Adobe Employee
May 3, 2018

Check the pom.xml as well. Make sure that you include the "junit" dependencies.

naveent23995593
Level 3
May 3, 2018