对于Actor的测试,可以使用TestActorRef和TestProb:
TestActorRef:用于获取Actor对象,能够获取actor中内部属性,使用方法underlyingActor(有泛型)
TestProb:用于判断actor接收消息后回应消息的判断,可以验证actor功能是否正常,使用方法expectMsg
具体使用示例参考如下:
package com.zte.sunquan.pipe;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.testkit.TestActor;
import akka.testkit.TestActorRef;
import akka.testkit.TestProbe;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Created by sunquan on 2017/12/19.
* Akka-testkit 的主要工具包括,
* 1) testProbe 用于测试 Actor 回应和发送消息,testActor 用于简便情况下测试 Actor 回应消息,
* 2) testActorRef 用于测试 Actor 内部状态的改变。
*/
public class PipeActorTest {
private static ActorSystem system;
@BeforeClass
public static void setUpClass() throws Exception {
System.setProperty("shard.persistent", "false");
system = ActorSystem.create("test");
}
@Test
public void testActor1() throws InterruptedException {
//回应消息的测试
TestProbe testProbe=new TestProbe(system);
ActorRef actorRef = system.actorOf(FirstActor.props(), "sunquan");
testProbe.send(actorRef,"sunquan");
testProbe.expectMsg("success");
Thread.sleep(5000);
}
@Test
public void testActor2() throws InterruptedException {
TestActorRef<FirstActor> actorRef = TestActorRef
.create(system, FirstActor.props(), "sunquan");
actorRef.tell("sunquan", ActorRef.noSender());
//actor内部状态的测试
Assert.assertEquals(actorRef.underlyingActor().getName(), "sunquan");
Thread.sleep(5000);
}
}