'Scala Test - Code with Await ignore the mocked future
I'm writing unit tests for a service method that returns a Future[Boolean].
Inside the code that I'm testing, there is an Await.result usage on a sequence of future.
class serviceLogic, method logic: Future[Boolean] -
val futureList: List[Future[Model]] = iterator.map { item =>
val handleResult: Future[Model] = handlerService.handle(item)
// do some logic
handleResult
}.toList
Await.result(Future.sequence(futureList), 1 minute)
// some logic
In the unit test that I'm writing, I'm mocking the handlerService to return a Future.successful for the handle method and I do see that it returns a successful result, but in the test, the Await.result waits till the duration ends and it ignores the mock of the calls, as the future didn't finish. While having the same test that returns a Future.failed(new RuntimeException), this is working as expected and the Await.result returns immediately
The test with the Future failed that works as expected:
"Some operation" should "should fail if handle failed" {
val someModel = Model()
when(handlerServiceMock).handle(anyString())
.thenReturn(Future.failed(new RuntimeException))
serviceLogic.logic().map { result =>
result mustBe false
}
}
But, this is not working for a successful future. the test looks like that:
"Some operation" should "should succeed if handle succeeded" {
val someModel = Model()
when(handlerServiceMock).handle(anyString())
.thenReturn(Future.successful(someModel))
serviceLogic.logic().map { result =>
result mustBe true
}
}
The test fails as it waits for the duration.
I do see in debug that for each handle the return is as expected Future(Success(model)), but the Future.sequence(futureList) is Future(not completed), so this is not working properly or I'm missing something...
Can you please help?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
