Actor测试用例一般写法

本文详细介绍了Akka框架中的测试工具,包括TestProbe和TestActorRef的使用方法。TestProbe用于验证Actor的消息发送和接收,而TestActorRef则用于检查Actor的内部状态。通过具体的示例代码,展示了如何使用这些工具进行Actor的测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值