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.

Mock vs Fake
In the context of unit testing, the distinction between mocks and fakes is subtle but important:
- Mocks are objects that verify behavior. They can only assert if certain methods were called with expected arguments.
- Fakes are simpler implementations that work like real components but with hardcoded or simplified logic.
I am fully aware that "mocks" is the term more familiar to most AEM developers. However, since as developers, we value clarity and precision, we'll use the correct terms throughout this article.
AEM Mocks
The AEM Mocks library made writing unit tests in AEM projects simpler and more fun by providing many reusable fakes. Reusable fakes included in the AEM context, such as ResourceResolver, Page, SlingHttpServletRequest, ValueMap, and others, allowed AEM developers to write unit tests with significantly less code.
The MockResourceResolver is a good example of a reusable fake object from the AEM Mocks library. It simulates the behavior of the real ResourceResolver used very often in AEM code, allowing developers to perform resource-related operations in unit tests without the need to add custom mocks or connect to an actual JCR repository.
private final AemContext context = new AemContext();
@BeforeEach
void setUp() {
context.create().resource("/content/example", "title", "Test Page");
}
@Test
void testResourceTitle() {
Resource resource = context.resourceResolver().getResource("/content/example");
assertEquals("Test Page", resource.getValueMap().get("title"));
}So why don't we follow the example of this amazing library, and build our own set of reusable fakes within our projects? I think we should, and it's actually quite simple to do. Therefore, let's go through one example together.
An Example
Method to Test
Imagine we need to write a unit test for a service that has just one method. This method checks if a user is an admin and returns a boolean.
public interface UserAccessService {
boolean checkIfUserIsAdmin(final ResourceResolver resourceResolver);
}Simple enough, but let's make it a bit more challenging. By looking at the method implementation, we realize it actually returns true in two cases:
- if the user is the default "admin" with unrestricted access (for local development)
- if the user is part of any of the administrator groups (for AEMaaCS environments)
Ok, still pretty simple method logic, but then we realize that the method relies on several internal APIs we would need to mock or fake to write our unit test:
- javax.jcr.Session
- org.apache.jackrabbit.api.security.user.UserManager
- org.apache.jackrabbit.api.security.user.Authorizable
- org.apache.jackrabbit.api.security.user.User
- org.apache.jackrabbit.api.security.user.Group
If we would write all of those mocks and fakes in our unit test class, it would become quite large and hard to read and understand. Therefore, let's try to write a clean unit test method without any mocks.
Unit Test for Admin
We'll start by creating a UserServiceAdminUserTest class and annotate it with @ExtendWith(AemContextExtension.class) so we can use AEM mocks. Now, we can create our test method. Here is how we want our test method to look like, we call the method under test and check the result, nothing else.
@Test
@DisplayName("GIVEN an admin user, "
+ "WHEN the administrator check is performed, "
+ "THEN it returns true")
void testAdminUser_IsAdministrator() {
final boolean result = userAccessService.
checkIfUserIsAdmin(context.resourceResolver());
assertTrue(result);
}Now, to avoid mocking inside our test method, we'll need a setup method to register our service and all the required mocks and fakes. In this example, we don't need to fake the Session, so we'll simply mock it. However, we do want to fake the UserManager so we can later reuse it to create test cases for other types of users.
private static final AemContext context = new AemContextBuilder().build();
private static UserAccessService userAccessService;
@BeforeAll
static void setup() {
userAccessService = context.registerService(UserAccessService.class, new UserAccessServiceImpl());
final Session session = Mockito.mock(Session.class);
context.registerAdapter(MockResourceResolver.class, Session.class, session);
final UserManager userManager = new UserManagerFake("admin", "administrators", true);
context.registerAdapter(MockResourceResolver.class, UserManager.class, userManager);
}Reusable Fakes
The last piece of the puzzle to make our test pass is to create the reusable fakes. Let's start by creating a UserManagerFake class in a separate package so other developers can later reuse it.
We'll make our fake class configurable and reusable by providing a few arguments in the constructor. We'll pass a userId, and groupId as strings, as well as an isAdmin boolean flag. This will be enough to test our service implementation with:
- the default "admin" user
- a user who is a part of any of the administrators groups
- a user who is a part of another group, but not administrators
But wait, UserManager is not the class providing those methods, so we'll simply pass those arguments down to a new UserFake class we need to create.
public class UserManagerFake implements UserManager {
private final String userId;
private final String groupId;
private final boolean isAdmin;
public UserManagerFake(final String userId, final String groupId, final boolean isAdmin) {
this.userId = userId;
this.groupId = groupId;
this.isAdmin = isAdmin;
}
@Override
public Authorizable getAuthorizable(final String s) throws RepositoryException {
return new UserFake(this.userId, this.groupId, this.isAdmin);
}
// Dummy overrides for all other methods in the interface
}Our service implementation uses only a few methods from the Authorizable and User interfaces, so we'll need to fake them by using the arguments received in the constructor.
public class UserFake implements Authorizable, User {
private final String userId;
private final String groupId;
private final boolean isAdmin;
public UserFake(final String userId, final String groupId, final boolean isAdmin) {
this.userId = userId;
this.groupId = groupId;
this.isAdmin = isAdmin;
}
@Override
public boolean isGroup() {
return false;
}
@Override
public String getID() throws RepositoryException {
return this.userId;
}
@Override
public boolean isAdmin() {
return this.isAdmin;
}
@Override
public Iterator<Group> declaredMemberOf() throws RepositoryException {
final List<Group> groupList = new ArrayList<>();
final Group group = new GroupFake(this.groupId);
group.addMembers(this.groupId);
groupList.add(group);
return groupList.iterator();
}
// Dummy overrides for all other methods in the interface
}Finally, we'll need to create one more fake class, a GroupFake to make our UserFake class compile.
public class GroupFake implements Authorizable, Group {
private final String groupId;
public GroupFake(final String groupId) {
this.groupId = groupId;
}
@Override
public String getID() throws RepositoryException {
return this.groupId;
}
@Override
public boolean isGroup() {
return true;
}
// Dummy overrides for all other methods in the interface
}Unit Test for Editor
Now that we have our reusable fakes in place, let's create another UserServiceEditorUserTest class and reuse our UserManagerFake. The only difference here is what arguments we pass to the constructor when creating our fake object.
@BeforeAll
static void setup() {
userAccessService = context.registerService(UserAccessService.class, new UserAccessServiceImpl());
final Session session = Mockito.mock(Session.class);
context.registerAdapter(MockResourceResolver.class, Session.class, session);
final UserManager userManager = new UserManagerFake("editor", "editors", false);
context.registerAdapter(MockResourceResolver.class, UserManager.class, userManager);
}
@Test
@DisplayName("GIVEN an editor user, not in the administrators group, "
+ "WHEN the administrator check is performed, "
+ "THEN it returns false")
void testEditorUser_IsAdministrator() {
final boolean result = userAccessService.
checkIfUserIsAdmin(context.resourceResolver());
assertFalse(result);
}By following this approach, our test methods become small, clean, and easy to understand.
Best Practices
Let's consider 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.
Finally, 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 and doing the classic when().thenReturn().
- 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.
Conclusion
By leveraging OSGi services, AEM developers can create reusable, maintainable, and consistent fakes that simplify unit testing. This approach reduces code duplication, enhances test understandability, and aligns with AEM’s modular architecture.
Start refactoring your tests today to harness the power of OSGi-based reusable fakes. Special thanks to two brilliant developers I had the pleasure of working with, who influenced the content of this article.


