如何在Java中模拟第三方API并测试缓存
我正在创建一个客户端,它使用异步缓存加载程序调用第三方API缓存数据,并每隔30分钟轮询一次数据,还使用该数据计算一些操作并返回结果 我想模拟第三方API,这样我就不必调用实际的API来测试它、缓存测试数据以进行测试、调用计算函数并获得测试结果 我的代码如何在Java中模拟第三方API并测试缓存,java,spring-boot,mockito,Java,Spring Boot,Mockito,我正在创建一个客户端,它使用异步缓存加载程序调用第三方API缓存数据,并每隔30分钟轮询一次数据,还使用该数据计算一些操作并返回结果 我想模拟第三方API,这样我就不必调用实际的API来测试它、缓存测试数据以进行测试、调用计算函数并获得测试结果 我的代码 private AsyncLoadingCache<String, Invocable> jsScriptCache; private void fetchJsScriptAndCache() { jsScript
private AsyncLoadingCache<String, Invocable> jsScriptCache;
private void fetchJsScriptAndCache() {
jsScriptCache = Caffeine
.newBuilder()
.maximumSize(10000)
.refreshAfterWrite(carbonClientProperties.getRefreshTimeDuration())
.buildAsync(
new AsyncCacheLoader<String, Invocable>() {
@Override
public @NonNull CompletableFuture<Invocable> asyncLoad(@NonNull String key, @NonNull Executor executor) {
log.debug("Script Key {} ", key);
String scriptUrl = carbonClientProperties.getBaseUrl() + "/static/evaluate.js";
log.debug("Script Url: {}", scriptUrl);
return carbonWebClient.get()
.uri(scriptUrl)
.exchange()
.transform(CircuitBreakerOperator.of(circuitBreaker))
.flatMap(clientResponse -> {
if (clientResponse.statusCode() == HttpStatus.NOT_FOUND) {
return clientResponse.toEntity(String.class).flatMap(
responseEntity -> Mono.just(null)
);
}
if (clientResponse.statusCode() != HttpStatus.OK) {
return Mono.error(new RuntimeException("Failed fetching from source "
+ key + " got response code: " + clientResponse.statusCode()));
}
return clientResponse.toEntity(String.class).flatMap(
responseEntity -> {
String script = responseEntity.getBody();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
engine.eval(script);
} catch (Exception e) {
e.printStackTrace();
log.debug("Unable to parse the js code");
}
Invocable invocableService = (Invocable) engine;
return Mono.just(invocableService);
}
);
})
.doOnSuccess(response -> log.debug("Response Struct: {} " + response))
.toFuture();
}
@Override
public @NonNull CompletableFuture<Invocable> asyncReload(@NonNull String key, @NonNull Invocable oldValue, @NonNull Executor executor) {
log.debug("Inside Reload {} ", key);
return Mono.fromFuture(asyncLoad(key, executor)).map(
script -> {
if (script == null || script.equals("")) {
return oldValue;
}
return script;
}
).onErrorReturn(oldValue).toFuture();
}
}
);
}
现在我想对它进行测试,并希望实际的API调用在从测试调用compute时发生
你能帮个忙吗
谢谢。可用于模拟第三方API
public Mono<Response> compute(String input) {
// I use the jsScriptCache.get to get the cache data and do some actions and return the
value of compute
}