1

我是 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
  }

}

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

4

1 回答 1

1

这样做的一种方法是等待结果或准备好(如果功能可能失败)然后运行您的代码(assert/shouldBe/etc.)

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

于 2016-07-10T15:10:05.593 回答