Search code examples
spring-bootazuremockitoazure-ad-b2cspring-boot-test

How to mock GraphServiceClient on SpringBootTest?


I have a method in my application that create a user on Azure AD B2C using Microsoft Graph REST API and I'd like to mock the GraphServiceClient to make some tests.

Java method that create user:

public User createUser(User user) throws ClientException {
        final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .tenantId(tenantId)
                .build();

        final TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(Arrays.asList(scope), clientSecretCredential);

        GraphServiceClient graphClient = GraphServiceClient.builder()
                .authenticationProvider(tokenCredentialAuthProvider)
                .buildClient();

        user.passwordPolicies = "DisablePasswordExpiration"; // optional
        PasswordProfile passwordProfile = new PasswordProfile();
        passwordProfile.forceChangePasswordNextSignIn = true; // false if the user does not need to change password
        passwordProfile.password = "xWwvJ]6NMw+bWH-d";
        user.passwordProfile = passwordProfile;

        return graphClient.users()
                .buildRequest()
                .post(user);
    }

How can I mock to return a user like when we use RestTemplate and use MockRestServiceServer


Solution

  • The best way to mock the GraphServiceClient should be by defining a way to override the bean returned by calling another method to get your GraphServiceClient

    // inside createUser method
    GraphServiceClient graphClient = buildGSC(tokenCredentialAuthProvider);
    
    // ...
    
    public static GraphServiceClient buildGSC(TokenCredentialAuthProvider tokenProvider) {
        return GraphServiceClient.builder()
                    .authenticationProvider(tokenProvider)
                    .buildClient();
    
    

    Then you should be able to mock this method using Powermock with your favorite mock tool (easymock / mockito) and test framework (junit / testng)