Expand my Community achievements bar.

Join us in celebrating the outstanding achievement of our AEM Community Member of the Year!

Null ponter exception while creating JUnit test case for CQ5 component-raising from getResource() method

Avatar

Level 1

Hi,

while i am trying to get current node value by mocking node class and ResourceResolver class I am getting nullPointerException over there.Exception is raising from getResource() method.

 

Here is my actual class code

public class Myclass extends WCMUse {

public void activate() throws Exception {

Node currentNode = getResource().adaptTo(Node.class);

.

.

..........bla bla

}

}

I am trying with 2 approaches 

Here is my first approach

    
    @Mock
    Node node;
    @Mock 
    ResourceResolver resourceResolver;
    

    @Test
        
        Resource res=resourceResolver.getResource("/");
        EasyMock.expect(res.adaptTo((Class<Node>) EasyMock.anyObject())).andReturn(node);

 

Here is my second approach

@Mock
    Node node;
    
    @Mock 
    ResourceResolver resourceResolver;
    
    @Mock
    private WCMUse wcmUse;
    
    @Mock
    private Resource r;

 r = wcmUse.getResource();


 node = r.adaptTo(Node.class);

 

In that underlined part I am getting null pointer Exception.

Please suggest me the exact approach to resolve this issue.

3 Replies

Avatar

Level 10

I think you should use @TestReference annotation

Avatar

Level 1

Thanks for your reply.

But i dont want to do sever side testing here.I want to use Junit and any mocking frameworks suggest me the approach in that, if posible.

Avatar

Level 2

Try using below approach:

Resource resource = mock(Resource.class);

MyClass myClass = new MyClass(){

   @Override
   public Resource getResource() {

   return resource;

  };

};