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 楼答案
这通常取决于如何编写可测试代码,而不是任何特定的模拟技术。在这里,我可以考虑以下方法使其可测试。因为
AsyncDocumentClient
是一个接口。为了使代码可测试,最好创建另一个用于创建文档客户端的接口,并将其注入代码中。这样,您就可以模拟新接口,它可以在测试时返回AsyncDocumentClient
的模拟。比如:DocumentClientFactory
(使用方法CreateAsyncClient
和实现DocumentClientFactoryImpl
。DocumentClientFactoryImpl
将在CreateAsyncClient
方法中具有实际的AsyncDocumentClient
创建逻辑CreateAsyncClient
,而不是内联客户端创建李>DocumentClientFactory
。mock将返回一个mockAsyncDocumentClient
,它具有测试所需的行为李>