Spock mocks for Akka's ActorRef

akka, groovy, scala, spock

Solution

The only supported way to mock an ActorRef is by creating a TestProbe:

// "system" is an ActorSystem
final TestProbe probe = TestProbe.apply(system);
final ActorRef mock = probe.ref;

It does not get easier or simpler than this.

Problem

I've tried to make an Spock test for a class, where i need to check that it sends a message to actor (say `statActor`). I know that Akka have special library for integration test, but seems that it's too much for very simple test. So, i've tried: ``` setup: def myActor = Mock(ActorRef) myService.statActor = myActor when: myService.startStats() then: 1 * myActor.tell(_) ``` Target method looks like: ``` void startStats() { Date x = null // prepare some data, fill x with required value this.statActor.tell(x) } ``` I thought that Spock will create mock with a method `tell`. But after running this test i'm getting: ``` java.lang.ClassCastException: akka.actor.ActorRef$$EnhancerByCGLIB$$80b97938 cannot be cast to akka.actor.ScalaActorRef at akka.actor.ActorRef.tell(ActorRef.scala:95) at com.example.MyService.startStats(MyService.groovy:32) ``` Why it's calling real `ActorRef` implementation? Some kind of incompatibility with Scala? Is there any way to make mock for such class?

Original source