Unit test for post sling servlet aem 6.5

I have the following POST servlet that adds new node under certain resource with parameters(name and last nam) from the request:

        service = Servlet.class,
        property = {
                "sling.servlet.methods=" + HttpConstants.METHOD_POST
public class CreateNodeServlet extends SlingAllMethodsServlet {

     * Logger
    private static final Logger log = LoggerFactory.getLogger(CreateNodeServlet.class);

    protected void doPost(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws IOException {
        log.info("Inside CreateNodeServlet");
        ResourceResolver resourceResolver = req.getResourceResolver();
        final Resource resource = resourceResolver.getResource("/content/test/us/en");
        String name = req.getParameter("name");
        String lastname = req.getParameter("lastname");
        log.info("name :{}",name);
        log.info("lastname :{}",lastname);

        Node node = resource.adaptTo(Node.class);
        try {
            log.info("Node {}", node.getName() );

            Node newNode = node.addNode(name+lastname, "nt:unstructured");
            newNode.setProperty("name", name);
            newNode.setProperty("lastname", lastname);

        } catch (RepositoryException e) {
        } catch (PersistenceException e) {
        resp.getWriter().write("Simple Post Test");

I tried creating unit test for this I got this so far:

class CreateNodeServletTest {

    private final AemContext context = new AemContext();

    private CreateNodeServlet createNodeServlet = new CreateNodeServlet();

    void doPost() throws IOException, JSONException {


        MockSlingHttpServletRequest request = context.request();
        MockSlingHttpServletResponse response = context.response();

        createNodeServlet.doPost(request, response);
        JSONArray output = new JSONArray(context.response().getOutputAsString());

        assertEquals("Simple Post Test", output);

however this is not working I am getting null pointer on this line

 Node node = resource.adaptTo(Node.class);

can some one help what I am missing and some tips will be of great help as I am new to AEM, and there is not much resources about unit testing sling servlets ?

1 answer

  • answered 2021-05-08 16:34 mkovacek

    I think you need to register JCR_MOCK as resource resolver type

    new AemContext(ResourceResolverType.JCR_MOCK);

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum