Expand my Community achievements bar.

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

How to write Junit test cases for content fragment

Avatar

Level 3

Hi All,

I have a sling model with a fragmentPath variable, using this variable I'm retrieving the content fragment data. how to write Junit test cases using Junit 5. Anybody can share your thoughts! 

@aanchal_sikka@arunpatidar , @HrishikeshKa 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Anilkumar9 ,

Writing JUnit test cases for a Sling Model that retrieves content fragment data involves several steps. Here’s a comprehensive guide on how to achieve this using JUnit 5.

Step-by-Step Guide

  1. Set Up Your Maven Dependencies: Make sure you have the necessary dependencies in your pom.xml for JUnit 5, Sling Models, and AEM Mocks. Here’s an example configuration:

 

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.models.api</artifactId>
    <version>1.4.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.models.impl</artifactId>
    <version>1.4.6</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.wcm.testing.aem-mock</groupId>
    <artifactId>aem-mock-junit5</artifactId>
    <version>2.5.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.7.1</version>
    <scope>test</scope>
</dependency>

 

Create the Sling Model: Assume you have a Sling Model that looks something like this:

 

import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

@Model(adaptables = Resource.class)
public class ContentFragmentModel {

    @ValueMapValue
    private String fragmentPath;

    public String getFragmentPath() {
        return fragmentPath;
    }

    // Method to retrieve content fragment data
    public String getContentFragmentData() {
        // Logic to retrieve content fragment data
        return "mockFragmentData";
    }
}

 

Write the JUnit Test Case: Here’s how you can write a JUnit 5 test case for the above Sling Model using AEM Mocks.

 

import io.wcm.testing.mock.aem.junit5.AemContext;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.spi.Injector;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;

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

@ExtendWith(AemContextExtension.class)
public class ContentFragmentModelTest {

    private final AemContext context = new AemContext();
    private ContentFragmentModel contentFragmentModel;

    @BeforeEach
    void setUp() {
        // Set up the resource
        context.create().resource("/content/testFragment",
                "fragmentPath", "/content/dam/myFragment");

        // Adapt the resource to the model
        Resource resource = context.resourceResolver().getResource("/content/testFragment");
        contentFragmentModel = resource.adaptTo(ContentFragmentModel.class);
    }

    @Test
    void testGetFragmentPath() {
        assertNotNull(contentFragmentModel);
        assertEquals("/content/dam/myFragment", contentFragmentModel.getFragmentPath());
    }

    @Test
    void testGetContentFragmentData() {
        assertNotNull(contentFragmentModel);
        assertEquals("mockFragmentData", contentFragmentModel.getContentFragmentData());
    }
}

 

  • Dependencies: We include necessary dependencies for Sling Models, AEM Mocks, and JUnit 5.
  • Sling Model: A simple Sling Model (ContentFragmentModel) is created with a field fragmentPath.
  • JUnit Test Case:
    • AemContext: AEM Mocks provide AemContext to simulate AEM environment.
    • Setup: In the setUp method, we create a resource and adapt it to our Sling Model.
    • Test Methods: We then write test methods to verify the functionality of our Sling Model.

Running the Tests

Ensure you run your tests using a Maven command like:

 

mvn clean test

 

This setup provides a foundation to write comprehensive unit tests for Sling Models that interact with content fragments in AEM. Adjust the ContentFragmentModel and test cases based on the actual logic and fields in your Sling Mode


View solution in original post

2 Replies

Avatar

Community Advisor

Hi @Anilkumar9 
You can try below:

 

Main

package com.myproject.core.models;

import com.adobe.cq.dam.cfm.ContentFragment;
import com.adobe.cq.dam.cfm.ContentFragmentManager;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;

import javax.annotation.PostConstruct;

@Model(adaptables = Resource.class)
public class ContentFragmentModel {

    @ValueMapValue
    private String fragmentPath;

    @SlingObject
    private Resource resource;

    private ContentFragment contentFragment;

    @PostConstruct
    protected void init() {
        if (fragmentPath != null) {
            Resource fragmentResource = resource.getResourceResolver().getResource(fragmentPath);
            if (fragmentResource != null) {
                ContentFragmentManager fragmentManager = resource.getResourceResolver().adaptTo(ContentFragmentManager.class);
                if (fragmentManager != null) {
                    contentFragment = fragmentManager.getFragment(fragmentResource);
                }
            }
        }
    }

    public ContentFragment getContentFragment() {
        return contentFragment;
    }
}



Test : Create a JUnit test class for your Sling Model. Use AEM Mocks to simulate the AEM environment.

package com.myproject.core.models;

import com.adobe.cq.dam.cfm.ContentFragment;
import com.adobe.cq.dam.cfm.ContentFragmentManager;
import io.wcm.testing.mock.aem.junit5.AemContext;
import org.apache.sling.api.resource.Resource;
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 org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@ExtendWith(AemContextExtension.class)
public class ContentFragmentModelTest {

    private final AemContext context = new AemContext();

    @Mock
    private ResourceResolver resourceResolver;

    @Mock
    private Resource fragmentResource;

    @Mock
    private ContentFragmentManager fragmentManager;

    @Mock
    private ContentFragment contentFragment;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);
        context.registerService(ContentFragmentManager.class, fragmentManager);
    }

    @Test
    void testContentFragmentModel() {
        String fragmentPath = "/content/dam/myproject/myfragment";

        // Set up the resource resolver mock
        when(resourceResolver.getResource(fragmentPath)).thenReturn(fragmentResource);
        when(fragmentResource.getResourceResolver()).thenReturn(resourceResolver);
        when(resourceResolver.adaptTo(ContentFragmentManager.class)).thenReturn(fragmentManager);
        when(fragmentManager.getFragment(fragmentResource)).thenReturn(contentFragment);

        // Load the test resource and adapt to the model
        context.create().resource("/content/test", "fragmentPath", fragmentPath);
        Resource resource = context.resourceResolver().getResource("/content/test");
        ContentFragmentModel model = resource.adaptTo(ContentFragmentModel.class);

        // Assert that the content fragment is not null
        assertNotNull(model);
        assertNotNull(model.getContentFragment());
    }
}


 



Arun Patidar

Avatar

Correct answer by
Community Advisor

Hi @Anilkumar9 ,

Writing JUnit test cases for a Sling Model that retrieves content fragment data involves several steps. Here’s a comprehensive guide on how to achieve this using JUnit 5.

Step-by-Step Guide

  1. Set Up Your Maven Dependencies: Make sure you have the necessary dependencies in your pom.xml for JUnit 5, Sling Models, and AEM Mocks. Here’s an example configuration:

 

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.models.api</artifactId>
    <version>1.4.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.models.impl</artifactId>
    <version>1.4.6</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.wcm.testing.aem-mock</groupId>
    <artifactId>aem-mock-junit5</artifactId>
    <version>2.5.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.7.1</version>
    <scope>test</scope>
</dependency>

 

Create the Sling Model: Assume you have a Sling Model that looks something like this:

 

import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

@Model(adaptables = Resource.class)
public class ContentFragmentModel {

    @ValueMapValue
    private String fragmentPath;

    public String getFragmentPath() {
        return fragmentPath;
    }

    // Method to retrieve content fragment data
    public String getContentFragmentData() {
        // Logic to retrieve content fragment data
        return "mockFragmentData";
    }
}

 

Write the JUnit Test Case: Here’s how you can write a JUnit 5 test case for the above Sling Model using AEM Mocks.

 

import io.wcm.testing.mock.aem.junit5.AemContext;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.spi.Injector;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;

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

@ExtendWith(AemContextExtension.class)
public class ContentFragmentModelTest {

    private final AemContext context = new AemContext();
    private ContentFragmentModel contentFragmentModel;

    @BeforeEach
    void setUp() {
        // Set up the resource
        context.create().resource("/content/testFragment",
                "fragmentPath", "/content/dam/myFragment");

        // Adapt the resource to the model
        Resource resource = context.resourceResolver().getResource("/content/testFragment");
        contentFragmentModel = resource.adaptTo(ContentFragmentModel.class);
    }

    @Test
    void testGetFragmentPath() {
        assertNotNull(contentFragmentModel);
        assertEquals("/content/dam/myFragment", contentFragmentModel.getFragmentPath());
    }

    @Test
    void testGetContentFragmentData() {
        assertNotNull(contentFragmentModel);
        assertEquals("mockFragmentData", contentFragmentModel.getContentFragmentData());
    }
}

 

  • Dependencies: We include necessary dependencies for Sling Models, AEM Mocks, and JUnit 5.
  • Sling Model: A simple Sling Model (ContentFragmentModel) is created with a field fragmentPath.
  • JUnit Test Case:
    • AemContext: AEM Mocks provide AemContext to simulate AEM environment.
    • Setup: In the setUp method, we create a resource and adapt it to our Sling Model.
    • Test Methods: We then write test methods to verify the functionality of our Sling Model.

Running the Tests

Ensure you run your tests using a Maven command like:

 

mvn clean test

 

This setup provides a foundation to write comprehensive unit tests for Sling Models that interact with content fragments in AEM. Adjust the ContentFragmentModel and test cases based on the actual logic and fields in your Sling Mode