Testing

Testing stream-based code might look complex because of the interconnectedness of all of the parts of the system. But more often than not testing streams boils down to unit-testing processing stages in isolation and relying on the Akka Streams that data flow between this stages will happen as expected.

Frequently, no special testing library is needed. Let's demonstrate this by testing our source:

"manager source" should {
"emit shopping lists as needed" in {
val future: Future[Seq[ShoppingList]] = Manager.manager.take(100).runWith(Sink.seq)
val result: Seq[ShoppingList] = Await.result(future, 1.seconds)
assert(result.size == 100)
}
}

In order to run this test snippet we need an implicit materializer to be in scope:

implicit val as: ActorSystem = ActorSystem("test")
implicit val mat: Materializer = ActorMaterializer()

The general approach is that in order to test a Sink it can be attached to the special Source, and for a Source under test, we'll need a special Sink.

In both cases, sequence-based Sources and Sinks are probably the most useful ones. In our example, we're testing that our source emits at least one hundred shopping lists and does this in a timely manner. The results are available as a Seq[ShoppingList] and can be inspected if needed.

In order to test a flow, we need to provide both a test Source and Sink:

"cook flow" should {
"convert flow elements one-to-one" in {
val source = Source.repeat(Dough(100)).take(1000)
val sink = Sink.seq[RawCookies]
val future: Future[Seq[RawCookies]] = source.via(Cook.formFlow).runWith(sink)
val result: Seq[RawCookies] = Await.result(future, 1.seconds)
assert(result.size == 1000)
assert(result.forall(_.count == 2))
}
}

Here, we see the same approach. After defining the test input and output we drive the flow under test and verify that the output has expected properties.

There is an undesirable call to Await.result in both cases which relates to the fact that running the Akka Streams flow produces a Future. We can improve on that by using testing techniques as described in Chapter 5, Property-Based Testing in Scala.

Alternatively, it is also possible to use test toolkits provided by other Akka libraries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.99.71