Search code examples
scalaakkaakka-streammockito-scala

Mockito mocking Akka Streams


When unit testing, what is the best approach to mocking out Akka Streams calls involving Sources, Flows and Sinks?


For example, the takeWhile function:

def takeWhile(p: Out => Boolean): Repr[Out]

Where Repr is a trait within a trait:

trait FlowOps[+Out, +Mat] {
  import akka.stream.impl.Stages._
  import GraphDSL.Implicits._

  type Repr[+O] <: FlowOps[O, Mat] {
    type Repr[+OO] = FlowOps.this.Repr[OO]
    type Closed = FlowOps.this.Closed
  }

If an object under test calls something like: mySource.takeWhile( ... ).runWith( ... ) I might need to mock it out...

How do you work out how to mock out, e.g., mock[Source[Any, Any]].takeWhile(*) returns mock[?]

The interactions between Source, Repr, FlowOps, and Out are unclear to me.

The source code for the FlowOps trait warns that it is internal and that one should not derive from it...does this affect mocking it?


Solution

  • You don't need to mock anything for basic tests with Akka Streams components; just use the testkit. For inspiration, check out the tests in the Akka repository. Here is an example from the FlowTakeWhileSpec:

    "take while predicate is true" in assertAllStagesStopped {
      Source(1 to 4).takeWhile(_ < 3).runWith(TestSink.probe[Int]).request(3).expectNext(1, 2).expectComplete()
    }