Writing tests for a Projection

Like other Pekko libraries, Projections ships with a @ref:TestKit that a user can include to assert the correctness of their Projection handler implementation. Add the Projections TestKit dependency to your project:

@@dependency [sbt,Maven,Gradle] { group=org.apache.pekko artifact=pekko-projection-testkit_$scala.binary.version$ version=$project.version$ }

Import the @apidoc[pekko.projection.testkit.(javadsl|scaladsl).ProjectionTestKit] and other utilities into a new @scala:[ScalaTest test spec] @java:[JUnit test].

Scala : @@snip ShoppingCartAppSpec.scala { #testKitImports }

Java : @@snip ShoppingCartAppTest.java { #testKitImports }

The TestKit includes several utilities to run the Projection handler in isolation so that a full projection implementation and source provider are not required.

  • @apidoc[pekko.projection.testkit.(javadsl|scaladsl).ProjectionTestKit] runs a projection with the test @apidoc[pekko.actor.typed.ActorSystem].
  • @apidoc[TestSourceProvider] allows the user to mock out test data Envelopes that will be processed by the Projection Handler.
  • @apidoc[TestProjection] is a test Projection implementation that uses an in-memory internal offset store.

Using these tools we can assert that our Projection handler meets the following requirements of the ItemPopularityProjectionHandler.

  1. Process each shopping cart item event, correctly calculate the item count delta, and update the database.
  2. Log the popularity of every 10th shopping cart item event that is processed.

Scala : @@snip ShoppingCartAppSpec.scala { #testKitSpec }

Java : @@snip ShoppingCartAppTest.java { #testKitSpec }