我是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
}
}
如果我更改代码只返回一个布尔值(更改相应的实现类),一切正常。否则结果是不确定的
答案 0 :(得分: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