0

Here is my code

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")
        }
    }
}

I have to write a test checking that if .entity().toStrict(5_000, materializer) timeout expires then onFailed("API Call Failed") is called. The current code do not call onFailed("") in case of timeout, therefore I want this test.

my test contains

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)
}

but I don;t know how to make toStrict() expire.

Lorenzo Belli
  • 1,767
  • 4
  • 25
  • 46

1 Answers1

0

As I understand from your question you can create mock object for ResponseEntity and create own implementation for toStrict() method that will have a delay. Something like in example below from here -> 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";
   }
});

Than you can set it in your response object.

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