How do we test Actors in Java?
The only thing I've seen so far is someone posting an example of testing a TypedActor. I take it there's no way of testing an UntypedActor through say Junit? Akka docs are getting开发者_开发技巧 better by the day, but I don't see testing mentioned. Is it really obvious and I'm just missing something?
For testing with JUnit you'll need to use the facilities provided by JUnit, the docs on testing Actor (Java equiv is UntypedActor) is here: http://akka.io/docs/akka/snapshot/scala/testing.html
It is possible, at least with version 1.3 and 2.0 and the akka-testkit library.
You do something like this to setup your actor:
@Before
public void initActor() {
actorSystem = ActorSystem.apply();
actorRef = TestActorRef.apply(new AbstractFunction0() {
@Override
public Pi.Worker apply() {
return new Pi.Worker();
}
}, actorSystem);
}
You can then use the TestProbe class to test your actor (for version 1.3 it is slightly different):
@Test
public void calculatePiFor0() {
TestProbe testProbe = TestProbe.apply(actorSystem);
Pi.Work work = new Pi.Work(0, 0);
actorRef.tell(work, testProbe.ref());
testProbe.expectMsgClass(Pi.Result.class);
TestActor.Message message = testProbe.lastMessage();
Pi.Result resultMsg = (Pi.Result) message.msg();
assertEquals(0.0, resultMsg.getValue(), 0.0000000001);
}
There is more available in a blogpost I wrote on some of my experiences: http://fhopf.blogspot.com/2012/03/testing-akka-actors-from-java.html
You might be interested in a blog post I've wrote: Testing AKKA actors with Mockito and FEST-Reflect The example I'm using is based on JUnit, Mockito, and FEST-Reflect. Let me know if that is useful to you.
精彩评论