Scalatest和scalamock,当涉及期货时,测试不通过



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

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

我已经在两个分支上执行了几次测试,"master"中的测试有时通过,"withNoFutures"中的测试总是通过。谁能帮我通过期货考试?

Github repo: 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
  }
}

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

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

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

相关内容

  • 没有找到相关文章

最新更新