Akka-Http:如何在测试中使HttpResponse严格实体超时

时间:2019-06-14 18:36:14

标签: kotlin akka akka-http

这是我的代码

import akka.http.javadsl.Http
// some initialization omitted

inline fun <reified T> executeRequest(request: HttpRequest, crossinline onError: (HttpResponse) -> Unit): CompletionStage<T?> {
    val unmarshaller = GsonMarshaller.unmarshaller(T::class.java)
    return http.singleRequest(request).thenCompose { httpResponse: HttpResponse ->
        if (httpResponse.status() == StatusCodes.OK || httpResponse.status() == StatusCodes.CREATED) {
            unmarshaller.unmarshal(httpResponse.entity().withContentType(ContentTypes.APPLICATION_JSON), dispatcher, materializer)
        } else {
            onError(httpResponse) // invoke lambda to notify of error
            httpResponse.discardEntityBytes(materializer)
            CompletableFuture.completedFuture(null as T?)
        }
    }
}

class TradingActor(
    val materializer: ActorMaterializer,
    val dispatcher: ExecutionContextExecutor
): AbstractLoggingActor() {

    fun submitNewOrder(request: Request, onFailed: (text: String) -> Unit) {
        executeRequest<OrderAnswer>(request) {
            it.entity().toStrict(5_000, materializer).thenApply { entity ->
                onFailed("API Call Failed")
            }
        }.thenAccept {
            println("OK")
        }
    }
}

我必须编写一个测试来检查如果.entity().toStrict(5_000, materializer)超时到期,则调用onFailed("API Call Failed")。当前代码不会在超时的情况下调用onFailed(""),因此我需要此测试。

我的测试包含

val response = akka.http.javadsl.model.HttpResponse.create()
    .withStatus(StatusCodes.OK)
    .withEntity("""{'s': 'text'}""")

Mockito.`when`(http.singleRequest(any()))
.then {
    CompletableFuture.completedFuture<akka.http.javadsl.model.HttpResponse>(response)
}

但是我不知道如何使toStrict()过期。

1 个答案:

答案 0 :(得分:0)

据您所知,您可以为ResponseEntity创建模拟对象,并为 toStrict()方法创建自己的实现,这会产生延迟。从下面的示例中开始-> Can I delay a stubbed method response with Mockito?

when(mock.load("a")).thenAnswer(new Answer<String>() {
   @Override
   public String answer(InvocationOnMock invocation){
     Thread.sleep(5000);
     return "ABCD1234";
   }
});

比起您可以在响应对象中进行设置而言。

val response = akka.http.javadsl.model.HttpResponse.create()
    .withStatus(StatusCodes.OK)
    .withEntity(mockedEntity)