【问题标题】:How to construct akka TestFSMRef with parameters?如何构造带参数的akka​​ TestFSMRef?
【发布时间】:2013-09-13 12:47:04
【问题描述】:

我正在尝试使用 information provided here 测试 Akka FSM。但是,当我的Actor with FSM 子类需要实例化参数时,我无法弄清楚如何创建TestFSMRef

对于标准的非 FSM 测试,我通过以下方式创建 TestActorRef

val testActor = TestActorRef(MyActorFSM.props("nl", p1, p2))

.props 方法是按照documented Recommended Practice 实现的。我尝试实例化一个testActor,然后将其传递给 TestFSMRef 构造函数:

val fsm = TestFSMRef(testActor)

但这不会编译:

inferred type arguments [Nothing,Nothing,akka.testkit.TestActorRef[Nothing]]
do not conform to method apply's type parameter bounds [S,D,T <: akka.actor.Actor]

【问题讨论】:

    标签: scala akka fsm


    【解决方案1】:

    从 akka 的示例 FSM 演员中窃取代码,我对其进行了一些调整,使其具有两个构造函数参数,现在看起来像这样:

    class MyFSMActor(foo:String, bar:Int) extends Actor with FSM[State,Data]{
      println(s"My foo = $foo and my bar = $bar")
      startWith(Idle, Uninitialized)
    
      when(Idle) {
        case Event(SetTarget(ref), Uninitialized) =>
          stay using Todo(ref, Vector.empty)
      }
    
      // transition elided ...
    
      when(Active, stateTimeout = 1 second) {
        case Event(Flush | StateTimeout, t: Todo) =>
          goto(Idle) using t.copy(queue = Vector.empty)
      }
    
      // unhandled elided ...
    
      initialize()
    }
    

    然后,我可以像这样为它创建一个测试引用:

    val test = TestFSMRef(new MyFSMActor("hello", 1))
    println(test.stateName)
    

    当我这样做时,我看到:

    My foo = hello and my bar = 1
    Idle
    

    您通常不会直接调用 Actors 构造函数(如果这样做会失败),但是将其包装在 TestActorRefTestFSMRef 中将允许您绕过该限制。我希望这可以帮助您使您的代码正常工作。

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 2016-11-12
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      相关资源
      最近更新 更多