Scala模拟:延迟Mockito.when()。thenReturn(someFuture)

时间:2019-05-13 19:12:51

标签: scala mockito delay future

val future = new CompletableFuture()
future.complete(someObject)

Mockito.when(_).thenReturn{
    future
}

对于上面的代码,我想测试val future中是否有延迟:CompletableFuture完成。

我该如何迫使未来推迟thenturn?

我尝试过类似的事情:

Mockito.when(_).thenReturn{
    Thread.sleep(2000)
    future
}

但不起作用

3 个答案:

答案 0 :(得分:3)

您可以使用thenAnswer代替thenReturn来模拟等待时间。

请参阅-https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/stubbing/Answer.html

以下是Java的等效代码-

Mockito.when(<your method call>).thenAnswer(new Answer<CompletableFuture>() {
   @Override
   public String answer(InvocationOnMock invocation){
      Thread.sleep(2000);
      return future;
   }
})

答案 1 :(得分:2)

您需要将Thread.sleep(2000)放在将来。

您可能想实现以下目标:

import java.time.Instant
import java.util.concurrent.CompletableFuture

import org.mockito.Mockito
import org.mockito.Mockito.when

object MainClass {

  def main(args: Array[String]): Unit = {

    val mock = Mockito.mock(classOf[SomeTrait])

    when(mock.doSmth).thenReturn(CompletableFuture.supplyAsync[String](() => {
      println(s"[${Instant.now()}] run future")
      try {
        Thread.sleep(2000)
        "Something"
      } finally {
        println(s"[${Instant.now()}] end future")
      }
    }))

    val future = mock.doSmth

    println(s"[${Instant.now()}] end main")
    future.get()
    println(s"[${Instant.now()}] result: ${future.get()}")
  }
}

trait SomeTrait {
  def doSmth: CompletableFuture[String]
}

输出:

[2019-05-13T20:55:34.079Z] end main
[2019-05-13T20:55:34.079Z] run future
[2019-05-13T20:55:36.096Z] end future
[2019-05-13T20:55:36.097Z] result: Something

P.S。当您声明要返回时,CompletableFuture的执行开始。如果您需要在此声明之后的某个时间开始执行future,则必须使用scala.concurrent.Promise并用scala.concurrent.Future包裹您的CompletableFuture

答案 2 :(得分:0)

使用模拟缩放,您可以编写类似的内容

when(_) thenAnswer {
   Thread.sleep(2000)
   future
}

可以说更干净,更容易理解