How to Mock ResourceResolver in Sling Model using AEMContext | Community
Skip to main content
Level 2
July 4, 2022
Solved

How to Mock ResourceResolver in Sling Model using AEMContext

  • July 4, 2022
  • 3 replies
  • 3871 views

hi experts,

 

May i know how to mock below code in Sling Model using AEMContext Mock, Thanks

 

@SlingObject

ResourceResolver resourceResolver.

 

Resource resource = resourceResolver.getResource("/content/dam/cf");

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by SantoshSai

Hi @shyams67489715 ,

Try this,

@ExtendWith(AemContextExtension.class)
public class ExampleTest {

private final AemContext context = new AemContext();

@BeforeEach
void setUp() throws Exception {
context.load().json("/path/to/your/json/resource.json", "/content/dam/cf");
}

@Test
public void testSomething() {
Resource resource = context.resourceResolver().getResource("/content/dam/cf");
// further testing
}
}

Hope that helps!

Regards,

Santosh

3 replies

SantoshSai
Community Advisor
SantoshSaiCommunity AdvisorAccepted solution
Community Advisor
July 4, 2022

Hi @shyams67489715 ,

Try this,

@ExtendWith(AemContextExtension.class)
public class ExampleTest {

private final AemContext context = new AemContext();

@BeforeEach
void setUp() throws Exception {
context.load().json("/path/to/your/json/resource.json", "/content/dam/cf");
}

@Test
public void testSomething() {
Resource resource = context.resourceResolver().getResource("/content/dam/cf");
// further testing
}
}

Hope that helps!

Regards,

Santosh

Santosh Sai
Ravi_Pampana
Community Advisor
Community Advisor
July 4, 2022

Hi,

 

You can add the json and map to the resource 

 

        public final AemContext ctx = new AemContext();

        ctx.load().json("/com/myproject/models/damresource/damFile.json", "/content/dam/cf");

        Resource mockDamResource = ctx.resourceResolver().getResource("/content/dam/cf");

       

ShaileshBassi
Community Advisor
Community Advisor
July 5, 2022

@shyams67489715 

The AemContext object provides access to mock implementations of:

  • OSGi Component Context
  • OSGi Bundle Context
  • Sling Resource Resolver
  • Sling Request
  • Sling Response
  • Sling Script Helper

Additionally it supports:

  • Registering OSGi services
  • Registering adapter factories
  • Accessing JSON Importer

Example

public class ExampleTest {

  @Rule
  public final AemContext context = new AemContext();

  @Test
  public void testSomething() {
    Resource resource = context.resourceResolver().getResource("/content/sample/en");
    Page page = resource.adaptTo(Page.class);
    // further testing
  }
}

The AEM mock context supports different resource resolver types (provided by the Sling Mocks implementation). Example:

private final AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

Reference: https://wcm.io/testing/aem-mock/usage.html

Thanks