Unit Test for for SlingServlet | Adobe Higher Education
Skip to main content
Level 6
December 2, 2021

Unit Test for for SlingServlet

  • December 2, 2021
  • 2 Antworten
  • 1900 Ansichten

Hi All

I need to write a UnitTest for a doGet method in a Servlet that extends SlingSafeMethodsServlet. 

 

This is the doGet method I need to write the UnitTest for and I am not sure how to mock the resource for it:

@Override
protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) throws IOException {
final JsonResponse jsonResponse = new JsonResponse(response);
final String title = request.getParameter("title");
final List<APIResult> locations = LocationFinderUtil.getLocationResultStream(request, searchService)
.filter(result -> StringUtils.isNotBlank(title) &&
(StringUtils.containsIgnoreCase(result.getTitle(), title) || StringUtils.containsIgnoreCase(result.getAdditionalAddress(), title)))
.map(APIResult::new)
.collect(Collectors.toList());
jsonResponse.write(locations);
}

 

Dieses Thema wurde für Antworten geschlossen.

2 Antworten

Hemalatha
Level 4
December 2, 2021

Hi @anasustic ,

 

For writing Junits for OSGi Code, You can go for Mockito framework and use AEMContext to mock the resources. Or you can use Sling Mocks- https://sling.apache.org/documentation/development/sling-mock.html

Please refer the below links for your reference, 

https://aemhints.com/2020/12/19/junit-test-in-aem-6-5-servlet/

https://myaemlearnings.blogspot.com/2020/07/unit-testing-hands-on-for-sling-servlet.html

https://www.youtube.com/watch?v=hY_b3d9VZ_k

 

 

 

Level 6
December 2, 2021

Hi @hemalatha 

Thanks for the reply. 

I am sorry but these two links are broken:

https://aemhints.com/2020/12/19/junit-test-in-aem-6-5-servlet/

https://myaemlearnings.blogspot.com/2020/07/unit-testing-hands-on-for-sling-servlet.html

 

If I use the AEMContext to mock the resource how do I build it using 

aemContext.build().resource()

 

Level 6
December 2, 2021

Hi @anasustic ,

 

The links are working. PFA. May be it was blocked if you are using VPN. Kindly check. Understand the Junit samples for servlet. How it has been written and note down the test cases for your servlet based on your use case, then write it by referring the samples is the best way. 

 


Thank you very much @hemalatha I will research the links from another location. It appears not to work from my current location.

arunpatidar
Community Advisor
Community Advisor
December 2, 2021
Level 6
December 3, 2021

Thanks @arunpatidar 

Your example is clear. I do however build a resource that is a page with several components. I am not sure if I can build a complex resource with context.

arunpatidar
Community Advisor
Community Advisor
December 4, 2021
Arun Patidar