【问题标题】:Scalatest and scalamock, tests not passing when Futures are involvedScalatest和scalamock,涉及Futures时测试不通过
【发布时间】:2016-07-11 00:01:26
【问题描述】:

我是 scalatest 和 scalamock 的新手,但我已经设法编写了一些测试。但是,当在我的测试(模拟返回结果和类本身)中使用 Futures 时,测试似乎没有通过。

我编写了一个托管在 github 上的最小工作示例。有两个分支,“master”涉及期货,“withNoFutures”不涉及。

我已经在两个分支上执行了几次测试,“master”中的测试有时会通过,“withNoFutures”中的测试总是通过。任何人都可以帮助我通过期货通过测试吗?

Github 仓库:https://github.com/vicaba/scalatestNotWorking/tree/master

失败的测试代码如下所示:

package example

import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfter, FunSuite}

import scala.concurrent.Future


class SomeServiceTest extends FunSuite with BeforeAndAfter with MockFactory {

  var otherService: SomeOtherService = _

  var service: SomeService = _

  before {
    otherService = mock[SomeOtherService]
    service = mock[SomeService]
  }

  after {
    otherService = null
    service = null
  }

  test("a first test works") {
    otherService.execute _ expects() once()
    service.execute _ expects(*) returning Future.successful(true) once()
    SomeService.execute(service, otherService)
  }


  // Why this test does not work?
  test("a second test works") {
    // Copy paste the code in the first test
  }

}

如果我将代码更改为仅返回一个布尔值(更改相应的实现类),一切正常。否则结果是不确定的

【问题讨论】:

    标签: future scalatest scalamock


    【解决方案1】:

    这样做的一种方法是等待结果或准备好(如果功能可能失败),然后运行您的代码(断言/应该/等)

    import scala.concurrent.Await
    import scala.concurrent.duration._
    
    //res0 is of type Future[T]
    val res0 = Await.ready(firstFeature, FiniteDuration(1,SECONDS))
    //res1 is of type T (from Future[T])
    val res1 = Await.result(secondFeature, FiniteDuration(1,SECONDS))
    

    另一种方法是在 ScalaTest 2.0 中使用 ScalaFuture here

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 1970-01-01
      • 2015-07-25
      • 2018-07-11
      • 2015-09-21
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 2021-03-02
      相关资源
      最近更新 更多