Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

AEM Unit Test for a component that uses a Service returning a list of paths based on a Query

Avatar

Level 8

Hi

I need to write a Unit Test for an AEM component that uses a service that returns a list of paths based on a Query. 

 

How do I write a Unit Test for such a method.

 

getBlogItemsForPaths(someService.findPages(filter), resource, blogContext);

 the someService returns a list of paths:

 

public List<String> someService(@Nonnull BlogArticleFilter filter) {
if (filter.getTagList().isEmpty()) {
return Collections.emptyList();
}

final String pathQuery = buildDesendantNodeString(filter.getPathList());
final String tagQuery = buildTagQuery(filter);
final String query = String.format(QUERY, pathQuery, Constants.TemplateType.BLOG_ARTICLE_PAGE.getTemplatePath(), tagQuery);

return resourceResolverUsageService.withServiceUserResourceResolver(ServiceUser.CONTENT_READER, resolver -> {
return StreamUtil.iteratorStream(resolver.findResources(query, Query.JCR_SQL2))
.sorted(Comparator.comparing(this::getDate, Comparator.reverseOrder()))
.map(Resource::getPath)
.filter(s -> !filter.getIgnoreList().contains(s))
.limit(filter.getMaxItems())
.collect(Collectors.toList());
});
}

 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi Anasustic,

 

Mockito is a wonderful library that let's you Mock any third party service that lives outside of your main class.

 

You can use @Mock annotation to mock any service you do not want to test in this particular tests and inject these into your @test with @RunWith(MockitoJunitRunnr.class) comand.

 

Some useful tutorials[1] [2]

[1] java - How to use Mockito with JUnit5 - Stack Overflow

[2] Unit testing | Adobe Experience Manager

 

Regards,

Peter

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

Hi Anasustic,

 

Mockito is a wonderful library that let's you Mock any third party service that lives outside of your main class.

 

You can use @Mock annotation to mock any service you do not want to test in this particular tests and inject these into your @test with @RunWith(MockitoJunitRunnr.class) comand.

 

Some useful tutorials[1] [2]

[1] java - How to use Mockito with JUnit5 - Stack Overflow

[2] Unit testing | Adobe Experience Manager

 

Regards,

Peter