Sling Mock is not allowing to get ResourceResolverFactory

1.3k Views Asked by At

Given code:

public class TestExample {
  @Rule
  SlingContext slingContext = new SlingContext(ResourceResolverType.JCR_MOCK);


  @Test
  public void test() {
    ResourceResolverFactory rrf = slingContext.getService(ResourceResolverFactory.class);
  }
}

Gives me:

org.apache.sling.resourceresolver.impl.ResourceResolverFactoryActivator$1 cannot be cast to org.apache.sling.api.resource.ResourceResolverFactory
java.lang.ClassCastException
    at example(ExampleTest.java:21)

Do I have to use slingContext.resourceResolver() method? It is not flexible as I want, because of existing only ResourceResolver instance at once (and it is closed on tearDown which my class is doing by itself). Can I avoid this problem somehow?

1

There are 1 best solutions below

0
On

The following code works for me

public class RRFTest {

    @Rule
    public final SlingContext slingContext = new SlingContext(ResourceResolverType.JCR_MOCK);

    @Test
    public void readRootWithRRF() throws LoginException {
        ResourceResolverFactory rrf = slingContext.getService(ResourceResolverFactory.class);
        ResourceResolver resolver = rrf.getAdministrativeResourceResolver(null);

        Resource resource = resolver.getResource("/");

        Assert.assertNotNull(resource);
    }
}

using the following dependencies

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.testing.osgi-mock</artifactId>
    <version>1.3.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.testing.jcr-mock</artifactId>
    <version>1.1.6</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.testing.sling-mock</artifactId>
    <version>1.3.0</version>
    <scope>test</scope>
</dependency>

What versions of Sling mocks are you using?