Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Junit5- adaptTo from context request is returning null

Avatar

Level 8

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

Level 9

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

 

Avatar

Level 8
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; } }

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