Introduction
Here is how we want our AEM test method to look like, we call the method under test and check the result, nothing else.
Are you ready to get rid of the when().thenReturn() noise from your test methods? Read the full article that explains this example in detail.
@Test
@DisplayName("GIVEN an admin user, WHEN the administrator check if performed, THEN it returns true")
void testAdminUser_IsAdministrator() {
final boolean result = userAccessService.checkIfUserIsAdmin(context.resourceResolver());
assertTrue(result);
}
Overview
When writing unit tests in Adobe Experience Manager (AEM), developers often mock or fake classes and methods using libraries like Mockito. While effective, this approach can become repetitive and difficult to maintain as the codebase grows. A more scalable solution lies within AEM itself: leveraging OSGi services to create reusable fakes.
OSGi services in AEM are inherently modular and designed to be easily injected and configured. This modularity makes them perfect for creating reusable fakes that can be shared across multiple test classes without duplicating code. Instead of repeatedly faking individual methods, we can fake the service by implementing its interface. Then, we can extend and reuse it later in other tests when needed.
Key Points
Here is how this approach affects our non-functional requirements:
- Reusability: Define mock logic once and use it across multiple tests.
- Consistency: Ensures uniform behavior in tests, reducing discrepancies.
- Maintainability: Centralized mock logic simplifies updates and maintenance.
- Integration: Seamlessly integrates with AEM’s dependency injection model.
In addition, let's mention a few additional best practices to follow:
- Centralize fakes: Keep fake services in a dedicated package like com.example.project.fakes so others can easily find and reuse them
- Use dependency injection: Always inject services in the context instead of creating mocks manually in test methods.
- Isolate test data: Parameterize fakes where needed to avoid hard-coded values.
- Keep it simple: Fake only the things you need for the method under test, and extend it later for new test cases.
Full Article
Read the full article on https://meticulous.digital/blog/f/reusable-fakes-in-aem-unit-tests to find out more.
Q&A
Please use this thread to ask questions relating to this article