Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

AEM QueryBuilder Junits

Avatar

Level 2

Hi,
We have a requirement to write Junits for Below code, can anyone please help us writing the code for junits for AEMAACS
Sample Code:

import com.adobe.granite.asset.api.Asset;
import com.adobe.granite.asset.api.AssetManager;
 
public static Map<String, Asset> getListOfAllAssetsFromQBVideo(ResourceResolver resolver, String assetFolderPath,String limitAll) throws RepositoryException
{
        QueryBuilder queryBuilder = resolver.adaptTo(QueryBuilder.class);
        Session session = resolver.adaptTo(Session.class);
        Map<String, String> predicate = new HashMap<>();
        predicate.put("path", assetFolderPath);
        predicate.put("type", EDAMConstants.DAM_ASSET);
        predicate.put("p.limit", limitAll);
        Query query = null;
        query = queryBuilder.createQuery(PredicateGroup.create(predicate), session);
        SearchResult searchResult = query.getResult();
        String path = "";
        Map<String, Asset> assetMap = new HashMap<>();
        for (Hit hit : searchResult.getHits()) {
            path = hit.getPath();
            Asset asset = resolver.getResource(path).adaptTo(Asset.class);
            assetMap.put(asset.getName(), asset);
        }
        return assetMap;
    }

Request you to please provide the sample junits code for above example

Thanks & Regards

 

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Vishal_Jain03 ,

You will have to mock queryBuilder in JUNIT class.
Sample code you can follow would look something like below:

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private QueryBuilder queryBuilder;

  @BeforeEach
    public void setup() throws LoginException {
        // setup mock service objects needed for the test
        context.registerService(QueryService.class, queryService, org.osgi.framework.Constants.SERVICE_RANKING,
                Integer.MAX_VALUE);   
        context.registerService(QueryBuilder.class, queryBuilder);
        // load test content
        context.load().json("<path-to-json-file>.json", "/content");
    }

    @Test
    public void testOutput() {
        Map<String, String> pageMap = new HashMap<>();
        pageMap.put("parent", "<page-path>");
        pageMap.put("comp", "root/<component-path>");
        pageMap.put("page", "p1");
        List<String> results = new ArrayList<>(Arrays.asList("/content/sample1",
                "/content/sample2"));

        SearchResults searchResults = new SearchResults();
        searchResults.setTotalResults('1');
        searchResults.setResults(results);

        String expectedResponse = "<mention-your-expected-response"
        String allItemsExpectedResponse = ""
        Resource resource = context.currentResource("/content/<sample-path>");
        when(queryService.executeSearchWithMetadata(any())).thenReturn(searchResults);
        when(<class-name>.getSearchResults(1, new String[0],null)).thenReturn(searchResults);
  assertEquals(2, <class-name>.generateOutput(resource, context.resourceResolver(), pageMap).size())
}

 

 

Thanks
Tarun

View solution in original post

4 Replies

Avatar

Community Advisor

Hi @Vishal_Jain03 , you can create mock objects for QueryBuilder, Query, and Session using

Mockito

// Mock objects
@Mock
private QueryBuilder queryBuilder;
@Mock
private Query query;
@Mock
private Session session;
@Mock
private SearchResult searchResult;

@Mock
private Asset asset;
//In setup method register adapters
@BeforeEach
void setUp() {
context.registerAdapter(ResourceResolver.class, Session.class, session);
context.registerAdapter(Resource.class, Asset.class, asset);
context.registerAdapter(ResourceResolver.class, QueryBuilder.class, queryBuilder); context.create.resource("/content/dam/sample");
}

//In test method
@Test
void testGetListOfAllAssetsFromQBVideo() throws RepositoryException{
// When-Then mocking
when(queryBuilder.createQuery(any(PredicateGroup.class), eq(session))).thenReturn(query); when(query.getResult()).thenReturn(searchResult);
when(searchResult.getHits()).thenReturn(hits);
when(asset.getName()).thenReturn("Sample");
when(hit.getPath()).thenReturn("/content/dam/sample"); // Call your method here
}

 This is a sample code, you can mock or update the code according to your requirements.

 

Hope this helps!!!

Avatar

Correct answer by
Community Advisor

Hi @Vishal_Jain03 ,

You will have to mock queryBuilder in JUNIT class.
Sample code you can follow would look something like below:

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private QueryBuilder queryBuilder;

  @BeforeEach
    public void setup() throws LoginException {
        // setup mock service objects needed for the test
        context.registerService(QueryService.class, queryService, org.osgi.framework.Constants.SERVICE_RANKING,
                Integer.MAX_VALUE);   
        context.registerService(QueryBuilder.class, queryBuilder);
        // load test content
        context.load().json("<path-to-json-file>.json", "/content");
    }

    @Test
    public void testOutput() {
        Map<String, String> pageMap = new HashMap<>();
        pageMap.put("parent", "<page-path>");
        pageMap.put("comp", "root/<component-path>");
        pageMap.put("page", "p1");
        List<String> results = new ArrayList<>(Arrays.asList("/content/sample1",
                "/content/sample2"));

        SearchResults searchResults = new SearchResults();
        searchResults.setTotalResults('1');
        searchResults.setResults(results);

        String expectedResponse = "<mention-your-expected-response"
        String allItemsExpectedResponse = ""
        Resource resource = context.currentResource("/content/<sample-path>");
        when(queryService.executeSearchWithMetadata(any())).thenReturn(searchResults);
        when(<class-name>.getSearchResults(1, new String[0],null)).thenReturn(searchResults);
  assertEquals(2, <class-name>.generateOutput(resource, context.resourceResolver(), pageMap).size())
}

 

 

Thanks
Tarun

Avatar

Level 6

Hi @Vishal_Jain03 

 

You will have to mock queryBuilder in JUNIT class.


you can also refer to this blog

https://taylor.callsen.me/unit-testing-aem-sling-models-and-servlets/ 

Hope this helps!