Spock mocks Akka ActorRef

I tried to run a Spock test for a class where I need to verify that it sends a message to the actor (say statActor ). I know that Akka has a special library for the integration test, but it seems that this is too much for a very simple test. So I tried:

 setup: def myActor = Mock(ActorRef) myService.statActor = myActor when: myService.startStats() then: 1 * myActor.tell(_) 

The target method is as follows:

 void startStats() { Date x = null // prepare some data, fill x with required value this.statActor.tell(x) } 

I thought Spock would create the layout using the tell method. But after running this test, I get:

 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 does it invoke a real implementation of ActorRef ? Some kind of incompatibility with Scala? Is there a way to mock such a class?

+7
source share
2 answers

The only supported way to mock ActorRef is to create a TestProbe:

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

It does not get easier or simpler.

+16
source

In specs2 you can do:

 val mockedActorRef = spy(TestProbe().ref) 

Then use it as usual.

0
source

All Articles