Skip to content
Advertisement

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.

JavaScript

I want to mock the KeyCloak methods in my test cases

for example

JavaScript

I want to mock somethig like below

JavaScript

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

Advertisement

Answer

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):

JavaScript

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

JavaScript

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
Advertisement