0

我已经开始为 scala actor 编写测试。我读了这个博客。http://blog.matthieuguillermin.fr/2013/06/akka-testing-your-actors/ 然后我开始了。我写了应用程序演员。但我意识到与其他人不同的应用程序参与者在博客中。因为演员是主班。它在控制台上写入字符串并向另一个参与者发送消息。如何测试应用程序参与者?

    class Application extends Actor{

      val cliCommandExecute = context.actorOf(Props[CLICommandExecute],"CLICommandExecute")
      println(Util.welcomeMessage)
      cliCommandExecute ! CLICommandExecute.Listen(self)

      def receive = {
        case CLICommandExecute.Done(result: String) => {
          println(result)
          cliCommandExecute ! CLICommandExecute.Listen(self)
        }
        case CLICommandExecute.Failed(result: String) => {
          println(result)
          println(Util.failedMessage)
          context.stop(self)
        }
        case CLICommandExecute.Exit => {
          println(Util.exitMessage)
          context.stop(self)
        }
      }
    }

我写了ApplicationTest。但是当我运行它时,测试结果失败了。

    class ApplicationTest  extends TestKit(ActorSystem("testSystem"))
      with WordSpecLike
      with Matchers {

        "A application actor" must {
          // Creation of the TestActorRef
          val actorRef = TestActorRef[Application]
          val result = "success"
          "receive messages" in {
            // This call is synchronous. The actor receive() method will be called in the current thread
            actorRef ! CLICommandExecute.Done(result)
            // This method assert that the testActorRef has received a specific message
            expectMsg("success")
          }
        }
    }     

错误如下:

    assertion failed: timeout (3 seconds) during expectMsg while waiting for success
    java.lang.AssertionError: assertion failed: timeout (3 seconds) during expectMsg while waiting for success

我该如何进行?

4

1 回答 1

0

要通过此处获取消息,expectMsg您应该发送响应而cliCommandExecute不是sender

  case CLICommandExecute.Done(result: String) => {
       println(result)
       cliCommandExecute ! CLICommandExecute.Listen(self)
  }

将其更改为:

 case CLICommandExecute.Done(result: String) => {
      println(result)
      sender() ! CLICommandExecute.Listen(self)
 }

您将通过 收到回复expectMsg

如果您想将响应发送给发送者而不是发送者,cliCommandExecute则应将其作为构造函数参数传递给您的Application演员:

class Application(cliCommandExecute: ActorRef) extends Actor { ...}

testActor并在您创建它时在您的测试通过中。这样,所有响应都将被定向到testActor,您可以通过expectMsg.

于 2015-08-06T12:36:39.580 回答