Skip to content

How to mock the Keycloak framework methods using Mockito in java

I’m the having functionality to fetch the following details from KeyCloak.

  1. User details
  2. Realm details
  3. Client details

I want to write the test cases for those functionalities using Mockito.

below is code logic for fetching those details.

private Keycloak keycloak;
private String realm;

public Optional<UserModel> getUsers(String userId) {
  UserResource userResource = keycloak.realm(realm).users().get(userId);
  if (userResource == null)
    return Optional.empty();
  UserRepresentation userRepresentation = userResource.toRepresentation();
  UserModel userModel = new UserModel(userRepresentation.getId(), userRepresentation.getFirstName(),
      userRepresentation.getEmail(), userRepresentation.isEnabled(),
      new Date(userRepresentation.getCreatedTimestamp()),
      new Date(userRepresentation.getCreatedTimestamp()),
  return Optional.of(userModel);

public Optional<RealmModel> getRealm(String realmId) {
  RealmResource realmResource = keycloak.realms().realm(realmId);
  if(realmResource == null)
    return Optional.empty();
  RealmRepresentation realmRepresentation = realmResource.toRepresentation();
  RealmModel realmModel = new RealmModel(realmRepresentation.getId(), realmRepresentation.getDisplayName());
  return Optional.of(realmModel);

public Optional<ClientModel> getClient(String clientId) {
  ClientResource clientResource = keycloak.realm(realm).clients().get(clientId);
  if(clientResource == null)
    return Optional.empty();
  ClientRepresentation clientRepresentation = clientResource.toRepresentation();
  ClientModel clientModel = new ClientModel(clientRepresentation.getClientId(), clientRepresentation.getName()) ;
  return Optional.of(clientModel);

I want to mock the KeyCloak methods in my test cases

for example

1. UserResource userResource = keycloak.realm(realm).users().get(userId);
2. UserRepresentation userRepresentation = userResource.toRepresentation();

I want to mock somethig like below


I don’t know is there any option available, Please help me to resolve the issue. Thanks



First you will need to have a constructor to receive autowired objects and values instead of adding these annotations on the fields (which is also a best practice):

// constructor
public YourBean(@Autowired Keycloak keycloak, @Value("${keycloak.realm}") String realm) {
    this.keycloak = keycloak;
    this.realm = realm;

After that, you will need to pass a mocked Keycloak object on the bean inside the test function:

Keycloak keycloak = Mockito.mock(Keycloak.class);
String realm = "mockedRealm";
YourBean bean = new YourBean(keycloak, realm);

So you can execute the Mockito.when functions. But pay attention that you will need to mock each function call in keycloak.realms().realm(realmId). Using Mockito.when chaining functions won’t work.

User contributions licensed under: CC BY-SA
6 People found this is helpful