Hi @ktnr ,
Sure, here's an example JUnit 5 test class for your Sling Model:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.models.factory.ModelFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
@ExtendWith({AemContextExtension.class, MockitoExtension.class})
@MockitoSettings(strictness = Strictness.LENIENT)
class ExpFragmentPathGetterTest {
private final AemContext context = new AemContext();
@Mock
private ResourceResolver resourceResolver;
@Mock
private ModelFactory modelFactory;
private ExpFragmentPathGetter slingModel;
@BeforeEach
void setUp() {
context.registerService(ResourceResolverFactory.class, mock(ResourceResolverFactory.class));
context.registerService(ModelFactory.class, modelFactory);
context.registerInjectActivateService(new ExpFragmentPathGetter());
slingModel = context.request().adaptTo(ExpFragmentPathGetter.class);
}
@Test
void testGetExpFragmentPath() {
// Set up mock resources
Resource source = mock(Resource.class);
Resource mainResource = mock(Resource.class);
// Set up mock behavior
when(resourceResolver.getResource("/path/to/source")).thenReturn(source);
when(source.getChild("resourceType")).thenReturn(mainResource);
when(mainResource.getPath()).thenReturn("/path/to/mainResource");
// Set up sling model properties
slingModel.path = "/path/to/source";
slingModel.resourceType = "resourceType";
slingModel.resourceResolver = resourceResolver;
// Test the method
String result = slingModel.getExpFragmentPath();
assertEquals("/path/to/mainResource", result);
}
}
```
This test class uses the AEM Mocks framework to set up a mock AEM context and mock resources for testing the Sling Model. The `@BeforeEach` method sets up the Sling Model and injects the necessary dependencies. The `@Test` method tests the `getExpFragmentPath()` method by setting up mock behavior for the `ResourceResolver` and calling the method with the appropriate parameters. The `assertEquals()` method checks that the expected result is returned.
Note that this is just an example and you may need to modify the test class to fit your specific use case. It's also recommended to consult with experienced AEM developers or solution architects to ensure that your test class is implemented correctly and follows best practices.