Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

how to get content fragment model name from contentfragment object

Avatar

Level 2

how to get content fragment model name from contentfragment object which support junit test case.
Note: contentFragment.getTemplate().getTitle() is not supportive in junit mocking.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@Sudarshan1992 

@Test
    void getContentFragmentTest() throws ContentFragmentException {
      final ContentFragment contentFragment = mock(ContentFragment.class);
      getValue(contentFragment, TITLE, "MyTitle");
      assertEquals("MyTitle", contentFragmentModel.getTitle());
}

private static void getValue(ContentFragment contentFragment, String key, String value) {
	ContentElement contentElement = mock(ContentElement.class);
	FragmentData fragmentData = mock(FragmentData.class);
	when(contentFragment.getElement(key)).thenReturn(contentElement);
	when(contentElement.getValue()).thenReturn(fragmentData);
	when(fragmentData.getValue()).thenReturn(value);
}

You might need to mock everything and try.
Was able to get the junit coverage with the above code. 
Hope this helps!

Thanks

View solution in original post

4 Replies

Avatar

Community Advisor

@Sudarshan1992 

you can get the content fragment model name from a content fragment object by calling the getTemplatePath()

 

Can you try below code 

 

import com.adobe.cq.dam.cfm.ContentFragment;
import org.junit.Test;

public class ContentFragmentTest {

@Test
public void testGetContentFragmentModelName() {
ContentFragment contentFragment = // Create or obtain a ContentFragment object
String modelName = contentFragment.getTemplatePath();
System.out.println("Content Fragment Model Name: " + modelName);
}

}

Avatar

Level 2

contentFragment.getTemplatePath(); --> this method itself doesnot exist with 

contentFragment.

Avatar

Correct answer by
Community Advisor

@Sudarshan1992 

@Test
    void getContentFragmentTest() throws ContentFragmentException {
      final ContentFragment contentFragment = mock(ContentFragment.class);
      getValue(contentFragment, TITLE, "MyTitle");
      assertEquals("MyTitle", contentFragmentModel.getTitle());
}

private static void getValue(ContentFragment contentFragment, String key, String value) {
	ContentElement contentElement = mock(ContentElement.class);
	FragmentData fragmentData = mock(FragmentData.class);
	when(contentFragment.getElement(key)).thenReturn(contentElement);
	when(contentElement.getValue()).thenReturn(fragmentData);
	when(fragmentData.getValue()).thenReturn(value);
}

You might need to mock everything and try.
Was able to get the junit coverage with the above code. 
Hope this helps!

Thanks