Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

Junit5- adaptTo from context request is returning null

Avatar

Community Advisor

Able to get the button (sling model) adapted in the Junit Test case with the below

 

 

 

@ExtendWith({ AemContextExtension.class, MockitoExtension.class })
public class ButtonTest {

	private final String RESOURCE_PATH = "/content/us/us/en/button";
	private final AemContext aemContext = new AemContext();
	private Button button;

	@BeforeEach
	void setUp() {
		aemContext.addModelsForClasses(Button.class);
		aemContext.load().json("/models/button.json", RESOURCE_PATH);
		button = aemContext.currentResource(RESOURCE_PATH).adaptTo(Button.class);
	}

 

 

 

 but it fails if I use 

 

 

 

@ExtendWith({ AemContextExtension.class, MockitoExtension.class })
public class ButtonTest {

	private final String RESOURCE_PATH = "/content/us/us/en/button";
	private final AemContext aemContext = new AemContext();
	private Button button;

	@BeforeEach
	void setUp() {
		aemContext.addModelsForClasses(Button.class);
		aemContext.load().json("/models/button.json", RESOURCE_PATH);
		aemContext.currentResource(RESOURCE_PATH);
          	button = aemContext.request().adaptTo(Button.class);
	}

 

 

 

Any pointers, what could have been missing in the second scenario? 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor
3 Replies

Avatar

Correct answer by
Community Advisor

Avatar

Community Advisor

@ShaileshBassi May be your sling model is not having SlingHttpServletRequest.class as abaptables and accepts only Resource.class.

 

Avatar

Community Advisor
package com.mysite.core.models;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = { Resource.class, SlingHttpServletRequest.class }, adapters = {
		Button.class }, resourceType = Button.RESOURCE_TYPE, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class Button {
	
	public static final String RESOURCE_TYPE = "mycompany/components/content/trainingbutton";
		
	@Inject
	private String label;

	@Inject
	private String linkTo;
@PostConstruct protected void init() { } public String getLinkTo() { return linkTo; } public String getLabel() { return label; } }

@Manu_Mathew_ I already have the same in my sling model, but still not able to adapt over here. Attaching the code snippet.