2015-04-14 79 views
2

我正在使用玩枚舉/枚舉器發送瀏覽器事件。我的事件是將被序列化爲JSON的案例類。我有類似下面的代碼:測試玩枚舉人

import play.api.libs.iteratee.{Enumeratee, Enumerator, Iteratee} 
import scala.concurrent.duration._ 
import scala.concurrent.{Await, ExecutionContext, Future} 
implicit val ex = ExecutionContext.global 


case class SomeClass(a: String, b: String, c: List[String]) 

val someEnumerator: Enumerator[SomeClass] = Enumerator.apply(
    SomeClass("a", "b", List("a", "b", "c")), 
    SomeClass("s", "a", Nil), 
    SomeClass("g", "g", Nil), 
    SomeClass("a", "T", List("a", "1", "c"))) 

val filtering: Enumeratee[SomeClass, SomeClass] = Enumeratee.filter[SomeClass](sc => sc.c.nonEmpty) 

val toJson: Enumeratee[SomeClass, String] = 
    Enumeratee.map[SomeClass] { 
    sc => 
     import org.json4s._ 
     import org.json4s.native.Serialization 
     implicit val formats = Serialization.formats(NoTypeHints) 
     Serialization.write(sc) 
    } 

val jsonStream: Enumerator[String] = someEnumerator &> filtering &> toJson 

我怎樣才能得到結果和測試filteringtoJsonjsonStream

回答

3

一個想法是運行Enumerator通過Iteratee收集結果,然後對結果應該是什麼斷言。您可以使用Iteratee.getChunksEnumerator[SomeClass]填入List[SomeClass]

// test filtering 
val filterResult: Future[List[SomeClass]] = someEnumerator &> filtering |>>> Iteratee.getChunks 

// Using the specs2 dsl just to illustrate my point. 
// This won't compile as-is, as `filterResult` is a `Future`, so we need to use 
// await to unwrap the `Future` and make our assertions. In specs2 I think 
// you can use filterResult.await..., but I'm not 100% sure. 
// You can also use Await.result(filterResult, Duration.Inf) 
filterResult.forall(_.c.nonEmpty) must beTrue 

// test json 
val jsonResult: Future[List[String]] = someEnumerator &> toJson |>>> Iteratee.getChunks 

// Use some assertion to match the JSON structure you get back.