我在模擬一個RxJava函數時會遇到一些麻煩,它會產生一些HTTP調用。我正在使用JUnit和Mockito。模擬RxJava異步http調用
//Customer.java extends ServiceManager
public Observable<String> getCustomerDetails(String uuidData){
String api = "http://someapi.com/" + uuidData;
return callHttps(api, getHeader(),
"",
HttpMethod.GET)
.doOnError(failure -> logger.error("Error was raised while calling Profile Save of ORCH API:"
+ failure.getMessage()))
.doOnNext(httpClientResponse -> {
logger.info("");
})
.concatMap(RxHelper::toObservable)
.reduce(Buffer.buffer(), Buffer::appendBuffer)
.map(buffer -> buffer.toString("UTF-8"))
.map(entries -> entries);
}
private MultiMap getProfileHeader(){
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
headers.add("Accept","application/json");
return headers;
}
public class ServiceManager {
@Inject
@Named("httpsClient")
private HttpClient httpsClient;
private static final Logger logger = LoggerFactory.getLogger(ServiceManager.class);
public Observable<HttpClientResponse> callHttps(String url, MultiMap headers, String body, HttpMethod httpMethod) {
return Observable.create(subscriber -> {
HttpClientRequest httpClientRequest = httpsClient.requestAbs(httpMethod, url);
httpClientRequest.exceptionHandler(event -> {
logger.error("Exception was raised :" + event.getMessage());
});
httpClientRequest.headers().addAll(headers);
RxHelper
.toObservable(httpClientRequest)
.subscribe(subscriber);
httpClientRequest.end(body);
});
}
}
如何嘲笑callHttps
功能,使其返回我HttpClientRequest
嘲笑迴應。對我來說另一種方法是使用WireMock,但我想通過嘲笑上面的函數來找到一種方法。
在我們的項目中,我們創建了真正的模擬服務,以證明精確的實時延遲以及可能的通信問題。據我所知,Mockito不能創建請求,它只會嘲笑。 – paul
除了擴展ServiceManager之外,您可能更願意將其作爲字段包含進來,然後使用依賴注入來注入ServiceManager的模擬實現,從而爲您提供僞造的http響應。 –