2016-06-28 74 views
1

我是scalatest和scalamock的新手,但是我设法编写了一些测试。但是,当我在测试中使用Futures(嘲笑返回的结果和课堂本身)时,测试看起来没有通过。Scalatest和scalamock,当期货涉及时测试未通过

我写了一个在github上托管的最小工作示例。有两个分支,“主”涉及期货和“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 
    } 

} 

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

回答

1

这样做的一个办法就是等待结果,或者准备(如果有可能失败),然后运行代码(断言/ 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 here