2016-06-28 71 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