【问题标题】:Unit Testing Scala Future Blocking Contexts单元测试 Scala 未来阻塞上下文
【发布时间】:2015-10-13 08:06:06
【问题描述】:

我有一段代码如下:

def someFunctioThatIWantToUnitTest() {
  val p = Promise[Int]()

  val result = getFutureInt(p)
  val resultFut = result.future

  // I extract the content in the resultFut and do what I want
  val didSomething = resultFut.get // not able to get here with my unit test
}

getFutureInt(...) 看起来像这样:

private def getFutureInt(promise: Promise[Int]) {
  blocking { // from the scala concurrent object
    // here I successfully return the promise with an Int value
    promise.success(2)
  }
}

假设有适当的 ExecutionContexts 可用,我想测试 someFunctioThatIWantToUnitTest 方法!当我尝试调试我的单元测试时,它不允许我进入阻塞块并且我的测试返回失败。有没有办法解决这个问题?

【问题讨论】:

    标签: scala unit-testing promise future


    【解决方案1】:

    scala.concurrent.Await.result 能解决你的问题吗?

    val myFuture = Future(1)
    val result: Int = Await.result(myFuture, 1.minute)
    

    还请记住,如果您的测试由于 Future.get 调用而提前失败,您可能永远无法捕获任何“未来”断点。这是因为测试可能会比您预期的更早停止,顺便破坏所有执行上下文。 (我不知道内部说 100%。)

    【讨论】:

      猜你喜欢
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多