代码之家  ›  专栏  ›  技术社区  ›  yotommy

如何用参数构造akka TestFSMRef?

  •  0
  • yotommy  · 技术社区  · 12 年前

    我正在尝试使用 information provided here 。但是,我不知道如何创建 TestFSMRef 当我的子类 Actor with FSM 需要用于实例化的参数。

    对于标准的非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]
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   cmbaxter    12 年前

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

    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
    

    您通常不会调用 Actor s构造函数(如果这样做,它将失败),但将其包装在 TestActorRef TestFSMRef 会让你绕过这个限制。我希望这能帮助您使代码正常工作。

    推荐文章