Expand my Community achievements bar.

SOLVED

How to Mock ResourceResolver in Sling Model using AEMContext

Avatar

Level 2

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");

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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

View solution in original post

3 Replies

Avatar

Correct answer by
Community Advisor

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

Avatar

Community Advisor

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");

       

Avatar

Community Advisor

@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