Expand my Community achievements bar.

SOLVED

how to write test cases for Servlet reading response boolean,

Avatar

Level 1

Tried with below approach getting errors not able to proceed further

Get method from Servlet:

 

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
 
ResourceResolver resourceResolver = request.getResourceResolver();
TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
String tagName = request.getParameter("tagName");
Tag tagPath = Objects.requireNonNull(tagManager).resolve(tagName);
Iterator<Tag> tagChildren = tagPath.listChildren();
String hasChildren = "false";
if (tagChildren.hasNext()) {
hasChildren = "true";
}
 
response.setContentType("text/plain");
response.getWriter().write(hasChildren);
}
 
 
 
Test cases for above method:
 
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
 
import com.day.cq.tagging.TagManager;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
 
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
 
@ExtendWith(AemContextExtension.class)
public class ServletTest {
 
    private SlingHttpServletRequest request;
    private SlingHttpServletResponse response;
    private ResourceResolver resolver;
    private TagManager tagManager;
    
    @BeforeEach
    void setup() throws IOException {
        request = mock(SlingHttpServletRequest.class);
        resolver = mock(ResourceResolver.class);
        response = mock(SlingHttpServletResponse.class);       
        when(request.getResourceResolver()).thenReturn(resolver);
        when(resolver.adaptTo(TagManager.class)).thenReturn(tagManager);
        PrintWriter writer = mock(PrintWriter.class);
        when(response.getWriter()).thenReturn(writer);
    }
    
    
    @test
    void testDoGet() throws IOException, ServletException {
    Servlet servlet = new Servlet();
        servlet.doGet(request, response);
        verify(response.getWriter()).write("true");
        verify(response.getWriter()).close();
    }
  
}
 
1 Accepted Solution

Avatar

Correct answer by
Level 5

I see you have mocked ResourceResolver & then trying to adapt it as TagManager, which will always throw NullPointer.

You will need to make use of AemContext to register the TagManager as an adapter

 e.g. 

aemContext.registerAdapter(ResourceResolver.class, TagManager.class, tagManager);
 
I would recommend using AemContext to get the ResourceResolver. Only mock objects which you can not adapt from AemContext.
e.g. 
resourceResolver = aemContext.resourceResolver();

View solution in original post

5 Replies

Avatar

Community Advisor

Hi @cheñak11958030 
Could you please check with assertTrue or assertFalse

 

assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);

assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);

 

Example

 

// Verify the response
assertEquals("false", response.getOutputAsString().trim());

import io.wcm.testing.mock.aem.junit5.AemContext;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.servlethelpers.MockSlingHttpServletRequest;
import org.apache.sling.servlethelpers.MockSlingHttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import javax.servlet.ServletException;
import java.io.IOException;

import static org.junit.jupiter.api.Assertions.assertEquals;

class YourServletTest {

    private AemContext context;
    private YourServlet servlet;

    @BeforeEach
    void setUp() {
        context = new AemContext();
        servlet = new YourServlet();
    }

    @Test
    void testDoGetWithChildren() throws ServletException, IOException {
        // Set up a mock request with parameters
        MockSlingHttpServletRequest request = context.request();
        request.addParameter("tagName", "yourTagName");

        // Set up a mock response
        MockSlingHttpServletResponse response = context.response();

        // Execute the servlet's doGet method
        servlet.doGet(request, response);

        // Verify the response
        assertEquals("true", response.getOutputAsString().trim());
    }

    @Test
    void testDoGetWithoutChildren() throws ServletException, IOException {
        // Set up a mock request with parameters
        MockSlingHttpServletRequest request = context.request();
        request.addParameter("tagName", "yourTagName");

        // Mock the tag resolution to simulate no children
        context.currentResource("/content/sample/tag"); // Assuming /content/sample/tag doesn't have children
        context.registerService(TagManager.class, new MockTagManager());

        // Set up a mock response
        MockSlingHttpServletResponse response = context.response();

        // Execute the servlet's doGet method
        servlet.doGet(request, response);

        // Verify the response
        assertEquals("false", response.getOutputAsString().trim());
    }

    // MockTagManager to simulate tag resolution without children
    private static class MockTagManager implements TagManager {
        @Override
        public Tag resolve(String tagId) {
            return new MockTag(tagId);
        }

        @Override
        public Tag resolve(Resource resource) {
            return new MockTag(resource.getPath());
        }
    }

    // MockTag to simulate a tag without children
    private static class MockTag implements Tag {
        private final String path;

        public MockTag(String path) {
            this.path = path;
        }

        @Override
        public String getPath() {
            return path;
        }

        @Override
        public String getTitle() {
            return null;
        }

        @Override
        public String getDescription() {
            return null;
        }

        @Override
        public String[] getTagID() {
            return null;
        }

        @Override
        public Iterator<Tag> listChildren() {
            return Collections.emptyIterator();
        }
    }
}

  

 



Arun Patidar

Avatar

Level 1

hi@arunpatidar thanks for the reply

 

       tried with your solution and its failing at

 

In Servlet:


String tagName = request.getParameter("tagName");
Tag tagPath = Objects.requireNonNull(tagManager).resolve(tagName);
Iterator<Tag> tagChildren = tagPath.listChildren();
String hasChildren = "false";
if (tagChildren.hasNext()) {
hasChildren = "true";
}

 

in Test Case

// Execute the servlet's doGet method
servlet.doGet(request, response);

test case:


import io.wcm.testing.mock.aem.junit5.AemContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.apache.sling.servlethelpers.MockSlingHttpServletRequest;
import org.apache.sling.servlethelpers.MockSlingHttpServletResponse;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.IOException;
import javax.servlet.ServletException;

class ElasticSearchServletTest {

private AemContext context;
private Servlet servlet;

@BeforeEach
void setUp() {
context = new AemContext();
servlet = new Servlet();
}

@Test
void testDoGetWithChildren() throws ServletException, IOException {
// Set up a mock request with parameters
MockSlingHttpServletRequest request = context.request();
request.addRequestParameter("tagName", "yourTagName");

// Set up a mock response
MockSlingHttpServletResponse response = context.response();

// Execute the servlet's doGet method
servlet.doGet(request, response);

// Verify the response
assertEquals("true", response.getOutputAsString().trim());
}

 

}





 




Avatar

Level 5

Can you also share the error where it fails ? I am guessing at  when(resolver.adaptTo(TagManager.class)).thenReturn(tagManager); ? But please share the full error output.

Avatar

Level 1

hi @anupampat 


Tag tagPath = Objects.requireNonNull(tagManager).resolve(tagName);

in Servlet doGet method 

cheak11958030_0-1709718581239.png

 




Avatar

Correct answer by
Level 5

I see you have mocked ResourceResolver & then trying to adapt it as TagManager, which will always throw NullPointer.

You will need to make use of AemContext to register the TagManager as an adapter

 e.g. 

aemContext.registerAdapter(ResourceResolver.class, TagManager.class, tagManager);
 
I would recommend using AemContext to get the ResourceResolver. Only mock objects which you can not adapt from AemContext.
e.g. 
resourceResolver = aemContext.resourceResolver();