gpt4 book ai didi

java - 模拟 RxJava 异步 http 调用

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:04 24 4
gpt4 key购买 nike

我在模拟进行一些 HTTP 调用的 RxJava 函数时遇到了一些麻烦。我正在使用 JUnit 和 Mockito。

//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,但我想通过模拟上述函数来找到一种方法。

最佳答案

假设 Customer 不必是最终的,您可以使用 Self-Shunt Pattern 。基本上,在这种模式中,您可以扩展被测类以使用新的模拟功能覆盖方法。因此,您可以扩展 Customer 并重写 callHttps(),这样它除了记录它被调用以便您可以验证它是否确实被调用之外,实际上不会执行任何操作。

请注意,我并不是提倡您应该像这样测试您的代码。通常使用此模式表示 code that could be restructured 。所以,如果可以的话,完全放弃继承权。话虽这么说,如果必须的话,请尝试使用类似于下面的示例代码的内容:

public class CustomerTest {
@Mock
private Observable<HttpClientResponse> mockObservable;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}

@Test
public void getCustomerDetailsCallsCallHttps() {
CustomerSelfShunt customerUnderTest = new CustomerSelfShunt();
// Call the getCustomerDetails method. Should call overridden version of
// callHttps() that sets callHttpsInvoked.
Observable<String> actualObservable = customerUnderTest.getCustomerDetails("foo");
assertEquals(this.mockObservable, actualObservable);
assertTrue(customerUnderTest.callHttpsInvoked);
}

private class CustomerSelfShunt extends Customer {
boolean callHttpsInvoked = false;

public Observable<HttpClientResponse> callHttps(String url, MultiMap headers, String body, HttpMethod httpMethod) {
// do nothing implementation, just record that this method was called.
callHttpsInvoked = true;
}
}
}

关于java - 模拟 RxJava 异步 http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40905375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com