Junit5- adaptTo from context request is returning null | Community
Skip to main content
ShaileshBassi
Community Advisor
Community Advisor
July 15, 2022
Solved

Junit5- adaptTo from context request is returning null

  • July 15, 2022
  • 2 replies
  • 1983 views

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? 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

2 replies

arunpatidar
Community Advisor
arunpatidarCommunity AdvisorAccepted solution
Community Advisor
July 15, 2022
Manu_Mathew_
Community Advisor
Community Advisor
July 16, 2022

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

 

ShaileshBassi
Community Advisor
Community Advisor
July 16, 2022
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.