MockitoJUnitRunner for junit in AemContext User adapation fails



Hi ,


I am using MockitoJUnitRunner for Junit .


I having the below code in java :-


In the below TestUser  class on the line

 resolver.adaptTo(User.class)  it fails and is always null how to resolve it 



public class TestUser {

private final ResourceResolver resolver;
private final User user;

public TestUser(final ResourceResolver resolver) {
this.resolver = resolver;
this.user= resolver.adaptTo(User.class);



Sling mode class:-

@Model(adaptables = {SlingHttpServletRequest.class, Resource.class},
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class TestClass {

private ValueMap properties;

private Node currentNode;

private SlingHttpServletRequest request;

private Resource resource;


private String appId;

public void initModel() {
//It is used below
TestUser user = new TestUser(request.getResourceResolver());


String appId=user.getAppId();



My Test class:-


I want to test the appId value that we get from slingmodel class as

resolver.adaptTo(User.class)  fails so cannot test


public class Testing {

private TestClass testClass;
private Resource resource;


public final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);

protected MockSlingHttpServletRequest request;

protected MockSlingHttpServletResponse response;

protected ResourceResolver resourceResolver;

protected Page page;

private TestUser testUser;

public void initialize() throws RepositoryException {
resource = context.create().

page = context.create().page("/content/abc");
request = context.request();
response = context.response();

slingBindings.put(SlingBindings.REQUEST, request);
slingBindings.put(SlingBindings.RESPONSE, response);
slingBindings.put(WCMBindings.CURRENT_PAGE, page);
slingBindings.put(WCMBindings.RESOURCE_PAGE, page);
slingBindings.put(WCMBindings.PAGE_PROPERTIES, resource.getValueMap());
slingBindings.put(WCMBindings.PROPERTIES, resource.getValueMap());
slingBindings.put(SlingBindings.RESOURCE, resource);
slingBindings.put(SlingBindings.SLING, context.slingScriptHelper());
slingBindings.put(WCMBindings.INHERITED_PAGE_PROPERTIES, resource.getValueMap());
slingBindings.put(SlingBindings.RESOLVER, resource.getResourceResolver());
request.setAttribute(SlingBindings.class.getName(), slingBindings);

TestClass = context.request().adaptTo(TestClass.class);


public void testMethod() {





Accepted Solutions (1)

Accepted Solutions (1)





It looks like you are attempting to write tests for constructor injection, please refer to this code snippet and example for how it can be achieved,


Secondly, Why are you adapting the resolver to a UserClass.class

TestUser user = new TestUser(request.getResourceResolver()); should be 

TestUser user = request.adaptTo(TestUser.class);

Checkout the code snippet and example for Unit Test for a Sling Model,


Answers (0)