Mocking a method in an actor class


(Sudeep Nagabhirava) #1

For doing unit tests, I am trying to mock a method which is defined in an actor class.
This is something I am trying to do

Actor actor = mock(Actor.class)
when(actor.methodInActor(any())).thenReturn(0);
System.out.println(actor.methodInActor());
// This prints 1 and hence it works

However, this is pretty much useless to me. What I am more interested about is,

TestActorRef ref = TestActorRef.create(testSystem,props, “testA”);
Actor actor = ref.underlyingActor()
when(actor.methodInActor(any())).thenReturn(0);
// This throws a Nullpointer exception

Actor actor = mock(ref.underlyingActor()) // This also throws an error

The reason why I was trying to do something like this is because my unit test tries to execute the actor with ref.tell(msg, testActor()) and I need to mock the method from an instance of the Actor Class

Any help will be appreciated


(Rob Crawford) #2

Why not subclass the Actor and have the subclass override the method to return 0? I’ve found test subclasses to be incredibly useful, especially when I want to use a TestProbe in place of a child actor that the production class creates.


(Brett Tofel) #3

Rob,

That’s sounds pretty cool. Could you provide example code?

-Brett