有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

junit如何模拟comosDB azure java集成客户端?

如何模拟cosmosDB JDK集成代码?下面是我的代码:

public String retrieveUserDetails() {
    ConnectionPolicy defaultPolicy = ConnectionPolicy.getDefaultPolicy();
    defaultPolicy.setUserAgentSuffix("CosmosDBJavaQuickstart");
    AsyncDocumentClient asyncClient = new AsyncDocumentClient.Builder()
            .withServiceEndpoint(AccountSettings.HOST)
            .withMasterKeyOrResourceToken(AccountSettings.MASTER_KEY)
            .withConnectionPolicy(defaultPolicy)
            .withConsistencyLevel(ConsistencyLevel.EVENTUAL)
            .build();

    String containerLink = String.format(DBS_COLLS, DB_NAME, USERROLEMAPPING);
    String sprocLink = String.format(SPROCS, containerLink, GETPROCS);
    final CountDownLatch successfulCompletionLatch = new CountDownLatch(1);
    String input = "{\"Email\":\""+userName+"\",\"Userid\" :\""+userId+"\"}";
    RequestOptions requestOptions = new RequestOptions();
    requestOptions.setPartitionKey(new PartitionKey(userId)); 
    logger.debug("input : {}", input);
    Object[] storedProcedureArgs = new Object[] { input };


    asyncClient.executeStoredProcedure(sprocLink, requestOptions, storedProcedureArgs)
            .subscribe(storedProcedureResponse -> {
                String storedProcResultAsString = storedProcedureResponse.getResponseAsString();
                    successfulCompletionLatch.countDown();
            }, error -> {
                successfulCompletionLatch.countDown();
                logger.debug("An error occurred while executing the stored procedure : actual cause ==>> {}", exceptionMsg);
            });
        return storedProcResultAsString;
}

使用来自https://cosmosdb.github.io/labs/java/technical_deep_dive/04-authoring_stored_procedures.html的代码

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    这通常取决于如何编写可测试代码,而不是任何特定的模拟技术。在这里,我可以考虑以下方法使其可测试。因为AsyncDocumentClient是一个接口。为了使代码可测试,最好创建另一个用于创建文档客户端的接口,并将其注入代码中。这样,您就可以模拟新接口,它可以在测试时返回AsyncDocumentClient的模拟。比如:

    • 将客户端创建分离为单独的接口及其实现。例如,接口DocumentClientFactory(使用方法CreateAsyncClient和实现DocumentClientFactoryImplDocumentClientFactoryImpl将在CreateAsyncClient方法中具有实际的AsyncDocumentClient创建逻辑
    • 在代码中注入DocumentClientFactory并调用CreateAsyncClient,而不是内联客户端创建
    • 在测试中,注入模拟的DocumentClientFactory。mock将返回一个mock AsyncDocumentClient,它具有测试所需的行为