Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock mocks for Akka's ActorRef

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?

like image 877
Igor Artamonov Avatar asked Jun 03 '12 08:06

Igor Artamonov


2 Answers

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.

like image 145
Roland Kuhn Avatar answered Jan 19 '23 04:01

Roland Kuhn


In specs2 you can do:

val mockedActorRef = spy(TestProbe().ref)

Then use it as normal.

like image 30
kflorence Avatar answered Jan 19 '23 03:01

kflorence