测试Play Enumeratee

时间:2015-04-14 12:03:39

标签: scala playframework

我使用Play Enumeratee / Enumerator发送浏览器事件。我的事件是将序列化为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

1 个答案:

答案 0 :(得分: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.