내 커뮤니티 업적 표시줄을 확대합니다.

Submissions are now open for the 2026 Adobe Experience Maker Awards.

Mark Solution

활동이 없어 이 대화는 잠겼습니다. 새 게시물을 작성해 주세요.

해결됨

wcm.io Junit4 Test - Sling Model Constructor

Avatar

이전 커뮤니티 멤버

Hello, I am having a problem where the resource is not injected into the Sling Model constructor during a test, I was able to inject mock services into the constructor, but unable to with the resource object (I do not wish to inject the Resource via Sling Model Annotations, as I want to use the  constructor only):

WebData Sling Model:

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

 SlingModel Unit Test:

@test
public void itShouldInject() {
     Resource resource = context.resourceResolver().getResource("/content/my-site/page/jcr:content/par/web");
     undertest =  resource.adaptTo(WebData.class);
}

 

1 채택된 해결책 개

Avatar

정확한 답변 작성자:
Community Advisor and Adobe Champion

Hey,

I know you said only constructor solutions, but I had a problem like this in the past, where It was extremely challenging to mock the Resource.class object into the constructor. Instead of initiating the Resource object dependency from the constructor, try using these Sling Model Annotations.

 

 

@Model
public class WebData {
   // this adapts the adaptable object into a resource object.
   @Deleted Account
   private Resource resource;
   
   //or

   @ScriptVariable
   // this calls on the current resource.
   Resource resource;
}

 

 

for other Sling Model annotations, checkout this blog https://sourcedcode.com/aem-sling-model-injectors-annotations-reference-guide

 

원본 게시물의 솔루션 보기

3 답변 개

Avatar

Community Advisor

Hi,

Can you try with -

 

private final AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

  

Arun Patidar

AEM LinksLinkedIn

Avatar

정확한 답변 작성자:
Community Advisor and Adobe Champion

Hey,

I know you said only constructor solutions, but I had a problem like this in the past, where It was extremely challenging to mock the Resource.class object into the constructor. Instead of initiating the Resource object dependency from the constructor, try using these Sling Model Annotations.

 

 

@Model
public class WebData {
   // this adapts the adaptable object into a resource object.
   @Deleted Account
   private Resource resource;
   
   //or

   @ScriptVariable
   // this calls on the current resource.
   Resource resource;
}

 

 

for other Sling Model annotations, checkout this blog https://sourcedcode.com/aem-sling-model-injectors-annotations-reference-guide

 

Avatar

이전 커뮤니티 멤버
thank you, I figured it out without the Constructer. this works!