mockito 如何在SpringBootTest上模拟GraphServiceClient?

yeotifhr  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(227)

我的应用程序中有一个方法,可以使用Microsoft Graph REST API在Azure AD B2C上创建用户,我想模拟GraphServiceClient来进行一些测试。
创建用户的Java方法:

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);
    }

字符串
我如何模拟返回一个用户,就像我们使用RestTemplateMockRestServiceServer一样

tquggr8v

tquggr8v1#

模拟GraphServiceClient的最佳方法应该是定义一种方法来覆盖通过调用另一个方法来获取GraphServiceClient所返回的bean

// inside createUser method
GraphServiceClient graphClient = buildGSC(tokenCredentialAuthProvider);

// ...

public static GraphServiceClient buildGSC(TokenCredentialAuthProvider tokenProvider) {
    return GraphServiceClient.builder()
                .authenticationProvider(tokenProvider)
                .buildClient();

字符串
然后,您应该能够使用Powermock和您最喜欢的模拟工具(easymock / mockito)和测试框架(junit / testng)模拟此方法。

相关问题