對於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);
}
}